0

问题 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)

这是为什么?

4

2 回答 2

3

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

像这样使用它:

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

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

于 2012-05-15T21:16:56.233 回答
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检查整个字符串是否从头到尾与您的模式匹配。

于 2012-05-15T21:17:24.487 回答