gpt4 book ai didi

java - 使用正则表达式java查找两个连续的单词/字符串(包括标点符号)

转载 作者:行者123 更新时间:2023-12-01 12:48:06 24 4
gpt4 key购买 nike

我想检查一个字符串是否包含两个按特定顺序直接跟随的单词/字符串。标点符号也应包含在单词/字符串中。 (即“单词”“单词”应作为不同的单词处理)。

举个例子:

    String word1 = "is";
String word1 = "a";
String text = "This is a sample";

Pattern p = Pattern.compile(someregex+"+word1+"someregex"+word2+"someregex");
System.out.println(p.matcher(text).matches());

这应该打印出true

对于以下变量,它也应该打印 true。

    String word1 = "sample.";
String word1 = "0END";
String text = "This is a sample. 0END0";

但后者在设置 word1 = "sample"(不带标点符号)时应返回 false。

有谁知道正则表达式字符串应该是什么样子(即我应该写什么而不是“someregex”?)

谢谢!

最佳答案

看起来您只是在空格上进行分割,请尝试:

Pattern p = Pattern.compile("(\\s|^)" + Pattern.quote(word1) + "\\s+" + Pattern.quote(word2) + "(\\s|$)");

说明

(\\s|^) 匹配第一个单词之前的任何空格,或字符串的开头

\\s+ 匹配单词之间的空格

(\\s|$) 匹配第二个单词之后的任何空格或字符串末尾

Pattern.quote(...) 确保输入字符串中的任何正则表达式特殊字符都被正确转义。

您还需要调用find(),而不是match()。仅当整个字符串与模式匹配时,match() 才会返回 true。

完整示例

String word1 = "is";
String word2 = "a";
String text = "This is a sample";

String regex =
"(\\s|^)" +
Pattern.quote(word1) +
"\\s+" +
Pattern.quote(word2) +
"(\\s|$)";

Pattern p = Pattern.compile(regex);
System.out.println(p.matcher(text).find());

关于java - 使用正则表达式java查找两个连续的单词/字符串(包括标点符号),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24489610/

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