【问题标题】:find two consecutive words/strings with regex expression java (including punctuation)使用正则表达式 java 查找两个连续的单词/字符串(包括标点符号)
【发布时间】:2014-08-20 19:03:39
【问题描述】:

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

举个例子:

    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”?)

谢谢!

【问题讨论】:

    标签: java regex word punctuation


    【解决方案1】:

    看起来你只是在空格上分割,试试:

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

    【讨论】:

    • 嗨杰米!谢谢您的回答!不幸的是,这不起作用.. String text = "This is a sample sentence.";字符串字符串=“样本”; String 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... :(
    • 我没有按照你的最后一个例子,word1word2text 的值是什么不起作用?
    • 抱歉,我没有更新您编辑的所有内容(没有 Pattern(quote))。现在有了您的回答和“find()”调用,一切正常!非常感谢!!
    • 再更新一次,允许两个单词之间有多个空格。
    【解决方案2】:

    您可以用空格连接这两个单词并将其用作正则表达式。 您唯一要做的就是替换“。”和 ”。”所以该点与任何字符都不匹配。

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

    【讨论】:

      猜你喜欢
      • 2019-01-05
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-18
      • 1970-01-01
      • 2015-08-26
      相关资源
      最近更新 更多