關於正則表達式 , 可以學習下這篇介紹 : 正則表達式
對於多次匹配, 正則表達式就需要講究些技巧了.
替換
單文的多次匹配
有以下幾種方式 , 把a
全匹配替換
替換 a
"aab".replaceAll("a{1}", "x"); //xxb
"aba".replaceAll("a{1}", "x"); //xbx
替換 aa
"abaaabaaaba".replaceAll("a{2}", "x"); //abxabxaba
"abaabaaaaba".replaceAll("a{2}", "x"); //abxbxxba
replaceAll()
方法會將所有匹配到的全部替換掉.
提取
提取就需要用到group
了.
提取 a
Matcher matcher = Pattern.compile("(a)").matcher("ab");
if(matcher.find()){
System.out.println(matcher.group());
}
--------
// 結果
a
提取多個 a
group
只有提取一次匹配到的 , 要多次提取 , 需要循環匹配.
Matcher matcher = Pattern.compile("(a)").matcher("aba");
int matcher_start = 0;
while (matcher.find(matcher_start)){
System.out.println(matcher.group(1));
matcher_start = matcher.end();
}
------------
// 結果
a
a
提取復雜內容
示例在一個文本中提取多個xml標簽
String txt = "abc123<root>這是root1</root><root>這是root2</root>";
Matcher matcher = Pattern.compile("<root>(.*?)</root>").matcher(txt);
int matcher_start = 0;
while (matcher.find(matcher_start)){
System.out.println(matcher.group(1));
matcher_start = matcher.end();
}
------
// 結果
這是root1
這是root2
group使用的注意點
多匹配和少匹配
上面的復雜示例中, 正則是 <root>(.*?)</root>
, 中間的分組匹配是 (.*?)
,里面是有個問號?
的 .
正則默認是多匹配的, 盡可能多的匹配到文本.
-
多匹配
那么不加
?
時, 只能匹配到一個文本 ,<root>(.*)</root>
匹配到的是:這是root1</root><root>這是root2
, 會把中間的全部匹配進去了. 這就是多匹配 -
少匹配
要盡可能少的匹配 , 就需要加上
?
,<root>(.*?)</root>
匹配到的是:這是root1
. 這個結果一般才是想要的.
group 匹配的組的順序
matcher.group(1) // 這里是group序號1
group
匹配后得到是一個數組 , 數組0位置是全匹配文本 , 數組1位置才是第一個匹配到的分組.
例如:
上面的示例中, <root>(.*?)</root>
得到的group(0)
是 <root>這是root1</root>
.
序號不好識別的話, 可以用別名來識別 .
String txt = "abc123<root>這是root1</root><root>這是root2</root>";
Matcher matcher = Pattern.compile("<root>(?<element>.*?)</root>").matcher(txt);
int matcher_start = 0;
while (matcher.find(matcher_start)){
System.out.println(matcher.group("element"));
matcher_start = matcher.end();
}
------
// 結果
這是root1
這是root2
element
就是文本的別稱 , 可以直接用別稱提取內容.
如果文章有幫助到您,請點個贊,您的反饋會讓我感到文章是有價值的