正則表達式的貪婪,勉強,獨佔模式


public static void main(String[] args) {
String s = "xxyyxxxyxxyxx";
Pattern greedy = Pattern.compile("xx(.*)xx");
Pattern reluctant = Pattern.compile("xx(.*?)xx");
Pattern possessive = Pattern.compile("xx(.*+)xx");
Matcher m1 = greedy.matcher(s);
Matcher m2 = reluctant.matcher(s);
Matcher m3 = possessive.matcher(s);
while(m1.find()) {
System.out.println("greedy..." + m1.group(1));
}
while(m2.find()) {
System.out.println("reluctant..." + m2.group(1));
}
while(m3.find()) {
System.out.println("possessive..." + m3.group(1));
}
}


輸出結果
greedy...yyxxxyxxy
reluctant...yy
reluctant...y

greedy (.*)喫掉整字符串,然後從最後一個字符開始回退,所以找到最後一個xx
reluctant (.*?)從左側開始匹配最少的字符,每當找到一個xx結尾就匹配一次
possessive (.*+)因爲喫掉整個字符串後面沒有xx,而且不會進行回退,所以沒有匹配到任何結果

一個用於替換字符串模式的例子:

public class StringAnalysis {
/**
* 將字符串中特定模式的字符轉換成map中對應的值
*
* @param s
* 需要轉換的字符串
* @param map
* 轉換所需的鍵值對集合
* @return 轉換後的字符串
*/
public static String convert(String s, Map<String, String> map) {
Matcher m = Pattern.compile("<#=(.*?)#>").matcher(s);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String value = map.get(m.group(1));
m.appendReplacement(sb, value != null ? value : "null");
}
m.appendTail(sb);
return sb.toString();
}

public static void main(String[] args) {
String str = "姓名:<#=name#>\n性別:<#=sex#>\n住址:<#=address#>\n聯繫方式:<#=linkinf#>";
Map<String, String> map = new HashMap<String, String>();
map.put("xxx", "哈哈");
map.put("name", "Steven");
map.put("address", "XX市XX區XXX二路X-X號X室");
map.put("linkinf", "13577777777");

System.out.println(convert(str, map));
}
}

輸出結果:
姓名:Steven
性別:null
住址:XX市XX區XXX二路X-X號X室
聯繫方式:13577777777
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章