String 類裏面matches()方法。
正則表達式通過一些特定的符號來體現規則,因此需要掌握其特定的符號。
雖然簡化了代碼,但是閱讀性變差。
1、正則表達式的規則:
字符類 | |
---|---|
[abc] | a、b 或 c(簡單類) |
[^abc] | 任何字符,除了 a、b 或 c(否定) |
[a-zA-Z] | a 到 z 或 A 到 Z,兩頭的字母包括在內(範圍) |
[a-d[m-p]] | a 到 d 或 m 到 p:[a-dm-p](並集) |
[a-z&&[def]] | d、e 或 f(交集) |
[a-z&&[^bc]] | a 到 z,除了 b 和 c:[ad-z](減去) |
[a-z&&[^m-p]] | a 到 z,而非 m 到 p:[a-lq-z](減去) |
預定義字符類 | |
---|---|
. | 任何字符(與行結束符可能匹配也可能不匹配) |
\d | 數字:[0-9] "\\d"寫於規則內 |
\D | 非數字: [^0-9] |
\s | 空白字符:[ \t\n\x0B\f\r] |
\S | 非空白字符:[^\s] |
\w | 單詞字符:[a-zA-Z_0-9] |
\W | 非單詞字符:[^\w] |
Greedy 數量詞 | |
---|---|
X? | X,一次或一次也沒有 |
X* | X,零次或多次 |
X+ | X,一次或多次 |
X{n} | X,恰好 n 次 |
X{n,} | X,至少 n 次 |
X{n,m} | X,至少 n 次,但是不超過 m 次 |
邊界匹配器 | |
---|---|
^ | 行的開頭 |
$ | 行的結尾 |
\b | 單詞邊界 |
\B | 非單詞邊界 |
\A | 輸入的開頭 |
\G | 上一個匹配的結尾 |
\Z | 輸入的結尾,僅用於最後的結束符(如果有的話) |
\z | 輸入的結尾 |
2、正則表達式對字符串的常見操作:
a、匹配
其實使用的就是String類中的matches方法。regexp="1[358]\\d{9}" 手機號碼檢驗
b、切割
其實使用的就是String類中的split方法。
String str="zhangsan xiaobai dashu";
String []names=str.split(" +");
for (String name:names)
System.out.println(name);
String str="zhangsan.xiaobai.dashu";
String []names=str.split("\\.");
String str="zhangsanttttttxiaobaihhhhhhdashu";
String []names=str.split("(.)\\1+");
組的概念,()然後想成自動生成組別名稱,從1開始。捕獲組可以通過從左到右計算其開括號來編號。例如,在表達式 ((A)(B(C))) 中,存在四個這樣的組:
1 ((A)(B(C))) 2 \A 3 (B(C)) 4 (C) 組零始終代表整個表達式。
c、替換
其實使用的就是String類中的replacAll()方法。
$對已有的正則表達式中的規則進行獲取。
String str="zhangsanttttttxiaobaihhhhhhdashu";
str=str.replaceAll("(.)\\1+","$1");
System.out.println(str);
String str="15832595623";
str=str.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
System.out.println(str);
d、獲取
示例:查找有三個字母的單詞!類 Pattern正則表達式的編譯表示形式。java.util.regex//將正則規則進行對象的封裝Pattern p = Pattern.compile("a*b");//通過正則對象的matcher方法字符串相關聯。獲取要對字符串操作的匹配器對象MatcherMatcher m = p.matcher("aaaaab");//通過Matcher匹配器對象的方法對字符串進行操作boolean b = m.matches();
String str = "da jia hao, ming tian bu fang jia";
String regex = "\\b[a-z]{3}\\b";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while ( matcher.find())
System.out.println(matcher.group());
3、正則表達練習:
a、治療口喫String text="我我..我我我...我我我我我..我要要要....要" +
"要要要..要要..學學學學學..學..編編..編編..編編...程程..程程";
text = text.replaceAll("\\.+","");
text = text.replaceAll("(.)\\1+","$1");
System.out.println(text);
b、對IP地址排序
String ip_str="192.168.10.34 127.0.0.1 3.3.3.3 105.70.11.55";
ip_str = ip_str.replaceAll("(\\d+)","00$1");
ip_str = ip_str.replaceAll("0*(\\d{3})","$1");
String []ips = ip_str.split(" +");
TreeSet <String >treeSet= new TreeSet<String>();
for (String i:ips)
{
treeSet.add(i);
}
for (String i:treeSet){
System.out.println(i.replaceAll("0*(\\d+)","$1"));
}
c、對郵件地址校驗
public static void main(String[] args) {
String mail = "[email protected]";
String regex ="[a-zA-Z0-9]\\w*@[a-zA-Z0-9]+(\\.[a-zA-Z]{1,3}){1,3}";
boolean b = mail.matches(regex);
System.out.println(mail+":"+b);
}
4、網絡爬蟲:
網絡爬蟲(又被稱爲網頁蜘蛛,網絡機器人,在FOAF社區中間,更經常的稱爲網頁追逐者),是一種按照一定的規則,自動地抓取萬維網信息的程序或者腳本。另外一些不常使用的名字還有螞蟻、自動索引、模擬程序或者蠕蟲。