2012-05-15 30 views
0

問題1:Java的正則表達式匹配,2個簡單的regex問題

String matchedKey = "sessions.0.something.else"; 
Pattern newP = Pattern.compile("sessions\\.([^\\.]+)(\\..+)"); 
m = newP.matcher(matchedKey); 

System.out.println(m.group(1)); // has nothing. Why? 

sessions\\. // word "sessions" followed by . 
([^\\.]+) // followed by something that is not a literal . at least once 
(\\..+)  // followed by literal . and anything at least once 

我本來期望的m.group(1)爲0

問題2

String mask = "sessions.{env}"; 
String maskRegex = mask.replace(".", "\\\\.").replace("env", "(.+)") 
            .replace("{", "").replace("}", ""); 
// produces mask "sessions\\.(.+))" 

當作爲

使用

這是爲什麼?

回答

2

之前,您可以訪問匹配的羣體,你必須調用matches就可以了:如果你想在字符串中的任何地方找到模式

String matchedKey = "sessions.0.something.else"; 
Pattern newP = Pattern.compile("sessions\\.([^\\.]+)(\\..+)"); 
m = newP.matcher(matchedKey); 
if (m.matches()) { 
    System.out.println(m.group(1)); 
} 

find也會做。 matches檢查整個字符串是否從頭到尾符合您的模式。

+0

完美!謝謝 – JAM

3

你有沒有叫你兩個問題Matcher.find()Matcher.macthes()方法。

使用方法如下:

if (m.find()) 
    System.out.println("g1=" + m.group(1)); 

還不錯檢查Matcher.groupCount()值。

+0

非常酷。謝謝 – JAM