gpt4 book ai didi

Java正则表达式与问号和单词边界完全匹配

转载 作者:行者123 更新时间:2023-11-30 07:54:07 26 4
gpt4 key购买 nike

在 java 中,我试图确定用户输入的字符串(意思是我不知道输入的内容)是否准确地包含在另一个字符串中,在单词边界上。所以 the 的输入不应该在文本中匹配 there is no match。但是,当输入的字符串中有标点符号时,我遇到了问题,需要一些帮助。

没有标点符号,这工作得很好:

String input = "string contain";
Pattern p = Pattern.compile("\\b" + Pattern.quote(input) + "\\b");

//both should and do match
System.out.println(p.matcher("does this string contain the input").find());
System.out.println(p.matcher("does this string contain? the input").find());

但是当输入中有问号时,与单词边界的匹配似乎不起作用:

String input = "string contain?";
Pattern p = Pattern.compile("\\b" + Pattern.quote(input) + "\\b");

//should not match - doesn't
System.out.println(p.matcher("does this string contain the input").find());

//expected match - doesn't
System.out.println(p.matcher("does this string contain? the input").find());

//should not match - doesn't
System.out.println(p.matcher("does this string contain?fail the input").find());

如有任何帮助,我们将不胜感激。

最佳答案

?之间没有单词边界,因为没有相邻的单词字符;这就是为什么你的模式不匹配。您可以将其更改为:

Pattern.compile("(^|\\W)" + Pattern.quote(input) + "($|\\W)");

匹配输入或非单词字符的开头 - 模式 - 输入或非单词字符的结尾。或者,更好的是,您使用负向后看和负向前视:

Pattern p = Pattern.compile("(?<!\\w)" + Pattern.quote(input) + "(?!\\w)");

这意味着,在你的模式前后不能有单词字符。

关于Java正则表达式与问号和单词边界完全匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44291367/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com