簡體   English   中英

用正則表達式表達式java查找兩個連續的單詞/字符串(包括標點符號)

[英]find two consecutive words/strings with regex expression java (including punctuation)

我想檢查一個字符串是否包含兩個單詞/字符串,然后直接按照特定順序進行。 標點符號也應包含在單詞/字符串中。 (即, “單詞”“單詞”。應作為不同的單詞處理 )。

舉個例子:

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

您可以將兩個單詞用空格連接起來,並將其用作正則表達式。 唯一要做的就是替換“。” 與“。” 因此該點與任何字符都不匹配。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM