2016-10-17 99 views
1

我想匹配使用java正則表達式的特定字符串模式。正則表達式相同的字符串匹配

我想找到的圖案像

{some stuff|other stuff} 

我現在用的是以下模式:

"(\\{#" + key + ")(\\|.*)[^\\}]" 

問題是,當我有類似:

text...  {some stuff|other stuff} {some stuff|other stuff} more text 

我匹配{some stuff|other stuff} {some stuff|other stuff}而不是2次{some stuff | other stuff}。

我認爲這是與正則表達式回溯有關,但我不知道如何解決它。

任何想法?

我的Java代碼:

Pattern pattern = Pattern.compile("(\\{#" + key + ")(\\|.*)[^\\}]"); 
Matcher m = pattern.matcher(string); 

while (m.find()) { 
    logger.info(m.group(0)); 
    //logger.warn("Parameter " + key + " is not found"); 
    // throw new Exception("Parameter " + key + " is not found"); 
} 
+0

什麼關於第二個模式已經匹配分裂? –

+0

什麼是鑰匙?你需要什麼確切的輸出(比如說,「{some stuff | other stuff}」)?請展示真實的例子。 –

+0

這個問題目前還不清楚。請提供一些您想要匹配的字符串以及預期的匹配組的具體示例。 –

回答

0

您可以使用string.matches("({"+key.replace('.',"\\.").replace('|',"\\|")+"|(.*)})+")

0

使用(\\{#" + key + ")(\\|)(.+?})作爲模式解決了我的問題。我沒有考慮到我的搜索行爲很貪婪。

謝謝你的回答,他們幫我解決了我的問題。

+0

如果你的'key'是說,'#我的*鍵',它將不起作用。或者,如果'|'後面的部分包含換行符。 –

0

您可以使用*-量化否定字符類別[^}]*,並且不要忘記將您傳遞給模式的變量字符串用作字面字符序列。

模式應該像

\{(#\Qmy.key\E)\|([^}]*)} 

regex demo

詳細

  • \{ - 字面{
  • (#\Qmy.key\E) - 第1組捕獲字面my.key
  • \| - 字面|
  • ([^}]*) - 組2捕獲0+字符其他比}
  • } - 字面}

online Java demo

String key = "my.key"; 
String s = "text...  {#my.key|other_stuff} {#my.key|new\nstuff} more\ntext"; 
Pattern pattern = Pattern.compile("\\{(#" + Pattern.quote(key) + ")\\|([^}]*)}"); 
Matcher m = pattern.matcher(s); 
while (m.find()) { 
    System.out.println("--- Match found ---"); 
    System.out.println(m.group(0)); 
    System.out.println(m.group(1)); 
    System.out.println(m.group(2)); 
} 
相關問題