Java Regex Matching,2个简单的正则表达式问题

时间:2012-05-15 21:07:14

标签: java regex

问题1。

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\\.(.+))"

用作

Pattern newP = Pattern.compile("sessions\\.(.+))"); // matches  matchedKey (above)
Pattern newP = Pattern.compile(maskRegex);          // does not match matchedKey (above)

为什么?

2 个答案:

答案 0 :(得分:3)

您在两个问题中都没有调用Matcher.find()Matcher.macthes()方法。

像这样使用:

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

检查Matcher.groupCount()值也很好。

答案 1 :(得分: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检查整个字符串是否与您的模式从开头到结尾匹配。