请考虑以下代码段:
String input = "Print this";
System.out.println(input.matches("\\bthis\\b"));
Run Code Online (Sandbox Code Playgroud)
产量
false
Run Code Online (Sandbox Code Playgroud)
这种方法可能有什么问题?如果它是错的,那么找到确切单词匹配的正确解决方案是什么?
PS:我在这里找到了各种类似的问题,但没有一个能提供我想要的解决方案.提前致谢.
DNA*_*DNA 38
当您使用该matches()方法时,它会尝试匹配整个输入.在您的示例中,输入"打印此"与模式不匹配,因为单词"打印"不匹配.
因此,您需要向正则表达式添加一些内容以匹配字符串的初始部分,例如
.*\\bthis\\b
Run Code Online (Sandbox Code Playgroud)
如果你想在行尾添加额外的文本:
.*\\bthis\\b.*
Run Code Online (Sandbox Code Playgroud)
或者,使用Matcher对象并使用在输入字符串中Matcher.find()查找匹配项:
Pattern p = Pattern.compile("\\bthis\\b");
Matcher m = p.matcher("Print this");
m.find();
System.out.println(m.group());
Run Code Online (Sandbox Code Playgroud)
输出:
this
Run Code Online (Sandbox Code Playgroud)
如果要在一行中找到多个匹配项,可以重复调用find()并group()提取所有匹配项.
匹配器的完整示例方法:
public static String REGEX_FIND_WORD="(?i).*?\\b%s\\b.*?";
public static boolean containsWord(String text, String word) {
String regex=String.format(REGEX_FIND_WORD, Pattern.quote(word));
return text.matches(regex);
}
Run Code Online (Sandbox Code Playgroud)
说明:
有关很好的解释,请参阅:http : //www.regular-expressions.info/java.html
myString.matches("regex") 返回 true 或 false 取决于字符串是否可以通过正则表达式完全匹配。重要的是要记住 String.matches() 只有在可以匹配整个字符串时才返回 true。换句话说:“regex”的应用就像你用字符串锚点的开头和结尾写了“^regex$”一样。这与大多数其他正则表达式库不同,如果正则表达式可以匹配字符串中的任何位置,则“快速匹配测试”方法返回 true。如果 myString 是 abc,则 myString.matches("bc") 返回 false。bc 与 abc 匹配,但 ^bc$(此处实际使用)不匹配。
这写“真”:
String input = "Print this";
System.out.println(input.matches(".*\\bthis\\b"));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
68732 次 |
| 最近记录: |