1

当我运行时:

String line = "  test";
Pattern indentationPattern = Pattern.compile("^[\\s]+");
Matcher indentationMatcher = indentationPattern.matcher(line);

if (indentationMatcher.matches()) {
    System.out.println("Got match!");

    int indent = indentationMatcher.group(0).length();
    System.out.println("Size of match: " + indent);
} else {
    System.out.println("No match! :(");
}

我没有比赛。这里发生了什么?我在http://www.regexplanet.com/advanced/java/index.html在线测试了正则表达式,这似乎是专门为在 Java 中测试正则表达式而设计的。

4

3 回答 3

6

改了几处,看评论:

String line = "  test";
Pattern indentationPattern = Pattern.compile("^(\\s+)"); // changed regex
Matcher indentationMatcher = indentationPattern.matcher(line);

if (indentationMatcher.find()) {   // used find() instead of matches()
    System.out.println("Got match!");

    int indent = indentationMatcher.group(1).length(); // group 1 instead of 0
    System.out.println("Size of match: " + indent);
} else {
    System.out.println("No match! :(");
}

输出:

Got match!
Size of match: 2

上述变化的原因:

find()尝试在输入中找到模式并true在找到时给出。也可以多次使用,例如while (matcher.find()) { ... }从输入中查找所有匹配项。

matches()尝试将完整输入与模式匹配,并且仅true在完整输入与正则表达式匹配时给出。

整个模式是第0组,第一个捕获组的内容是第1()组。在这种情况下没有区别,因为在捕获组之外,只有行的开头^,其长度/宽度为0。

于 2013-02-21T16:04:00.677 回答
1

Matcher#matches 自动锚定给定的模式,这意味着首先它与它"^[\\s]+"完全相同"[\\s]+"。因此,要匹配您的输入,只需使用"[\\s]+.*".

于 2013-02-21T16:03:34.303 回答
1

Matcher.matches()尝试匹配整个字符串,但您的模式只匹配空格而不匹配其他内容。尝试

Pattern indentationPattern = Pattern.compile("(\\s+).*")

反而。如果模式匹配,group(1)则将包含前导空格。如果您还对其余字符感兴趣,则必须添加另一个捕获组。

于 2013-02-21T16:12:20.120 回答