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

使用正则表达式java(包括标点符号)查找两个连续的单词/字符串,java,regex,word,punctuation,Java,Regex,Word,Punctuation,我想检查一个字符串是否包含两个单词/字符串,它们是否按特定顺序直接跟在后面。 单词/字符串中还应包含标点符号。(即“单词”和“单词”。应作为不同的单词处理 例如: String word1 = "is"; String word1 = "a"; String text = "This is a sample"; Pattern p = Pattern.compile(someregex+"+word1+"someregex"+word2+"someregex")

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

例如:

    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

    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());

您可以用空格连接这两个单词,并将其用作regexp。 您必须做的唯一一件事是将“.”替换为“.”,这样该点就不会与任何字符匹配

String regexp = " " + word1 + " " + word2 + " ";
regexp = regexp.replaceAll("\\.", "\\\\.");

嗨,杰米!谢谢你的回答!不幸的是,这不起作用。。String text=“这是一个示例句子。”;String=“sample”;string2=“句子。”;模式p=Pattern.compile(“\\s |^”+string+“\\s”+string2+“\\s |$”);System.out.println(p.matcher(text.matches());打印出来的是假的。。。除了设置string=“is”和string2=“a”这两个对我来说似乎很奇怪的选项之外……更接近,但不幸的是,这两个选项不起作用。。。正在尝试word1=“a”;和word2=“sample.NoSpace”;应该返回false而不是true…:(我没有遵循上一个示例,
word1
word2
text
的值是什么?很抱歉,我没有更新您编辑的所有内容(没有模式(引号))。现在就用您的答案和“find()”电话,一切都很好!非常感谢!!再更新一次,允许两个单词之间有多个空格。