簡體   English   中英

正則表達式的末尾有一個轉義的右括號

[英]Regular expression wtih an escaped closing bracket at the end

這是一個Java /正則表達式問題。

我喜歡使用以下代碼段在Java程序的文本字符串中搜索"M(x)"

public static List<String> findPattern(String patternStr, String value)
{
    ArrayList<String> matchedStrings = new ArrayList<String>(5);
    Pattern pattern = Pattern.compile(patternStr);          
    Matcher matcher = pattern.matcher(value);
    while (matcher.find()) {
        matchedStrings.add(matcher.group(0));
    }
    return matchedStrings;
}

以下模式字符串有效:

M\\\\(x\\\\)

以下模式沒有:

\\\\bM\\\\(x\\\\)\\\\b

我喜歡使用\\\\b以便找到文本為"M(x) = abc"而不是"TM(x) = abc"的匹配項。 真的很有趣,在進行了所有測試之后, "\\\\b"似乎只有在前面的字符是轉義括號時才會失敗。

我有做錯什么嗎? 還是有可以實現相同目標的東西?

謝謝並恭祝安康

請參閱\\ b是單詞邊界錨 換句話說,它在單詞字符(字母,數字,下划線)和非單詞字符(其余)之間標記了一個位置。

關鍵是,')'和''(空格字符)都是非單詞字符,因此它們之間沒有單詞邊界。 如果您期望在您的模式中使用它,它將失敗。

因此,您可以從模式中刪除尾隨\\ b,將其變成...

 \\bM\\(x\\)

結尾\\b在您的情況下不起作用,因為\\b匹配:

如果字符串中的最后一個字符是單詞字符,則在字符串的最后一個字符之后。 http://www.regular-expressions.info/wordboundaries.html

為什么需要第二個\\b 您可以提供不同的測試用例和預期結果嗎?

試試這個.*?(M\\(x\\)) .*? 表示非貪婪匹配。

String txt="sdda2asddaTM(x) = abcsdssdcxc";
    Pattern p = Pattern.compile(".*?(M\\(x\\))", Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(txt);
    if (m.find()) {
        System.out.print(m.group(1));
    }

您不會得到TM(x)

暫無
暫無

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

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