简体   繁体   English

正则表达式与单词模式不匹配

[英]Regular expression not matching word pattern

I have written code in Java which will return true if the matching string contains word or words. 我在Java编写的代码将返回true如果匹配字符串中包含的字或词。 But it is returning false . 但是它返回false

public class RegexTestStrings {
  public static final String EXAMPLE_TEST = "This is my small example "
      + "string which I'm going to " + "use for pattern matching.";

  public static void main(String[] args) {
    System.out.println(EXAMPLE_TEST.matches("(\\w)*"));
  }
}

Can anyone spot my mistake? 谁能发现我的错误?

matches() tests the entire string. matches()测试整个字符串。 You need to use find() or extend your regex with .* : 您需要使用find()或使用.*扩展正则表达式:

.*(\\w)+.*

Please note, that I changed * to + . 请注意,我将*更改为+

I would prefer find() for performance reasons. 由于性能原因,我希望使用find()

如果您只需要测试字符串是否匹配并且不需要获取组,就足够了

".*\\w+.*"

正如您在文档中看到的,\\ w匹配字母和数字,而不是空格或符号。

From the javadoc javadoc

\\w A word character: [a-zA-Z_0-9] \\ w一个字字符:[a-zA-Z_0-9]

As you see there is no space, no single quote and no dot. 如您所见,没有空格,没有单引号和点。 So your regexp cannot match the test string since it contains those charachtes. 因此,您的正则表达式无法匹配测试字符串,因为它包含那些字符。

The following prints true for your test string 以下为您的测试字符串显示为true

System.out.println(EXAMPLE_TEST.matches("(\\w|\\s|\\p{Punct})*"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM