2013-01-16 31 views
1

我需要不受字符限制的字符串的java模式。
字符串的正則表達式模式不受字符限制

我有一個字符串(如下所述),一些花括號括在單引號和其他大括號內。我想用另一個字符串替換不受單引號限制的大括號。

原始字符串:

this is single-quoted curly '{'something'}' and this is {not} end 

需要轉換到

this is single-quoted curly '{'something'}' and this is <<not>> end 

注意,大括號{}不是由單引號包圍已被替換< < >>。

然而,我的代碼打印(字符被吃掉)的文本

this is single-quoted curly '{'something'}' and this is<<no>> end 
當我使用模式

[^']([{}]) 

我的代碼是

String regex = "[^']([{}])"; 
Pattern pattern = Pattern.compile(regex); 
Matcher matcher = pattern.matcher(str); 

while (matcher.find()) { 
    if ("{".equals(matcher.group(1))) { 
     matcher.appendReplacement(strBuffer, "&lt;&lt;"); 
    } else if ("}".equals(matcher.group(1))) { 
     matcher.appendReplacement(strBuffer, "&gt;&gt;"); 
    } 
} 
matcher.appendTail(strBuffer); 

回答

3

這是一個明顯的用例零寬度斷言。你所需要的正則表達式是不是很複雜:

String 
    input = "this is single-quoted curly '{'something'}' and this is {not} end", 
    output = "this is single-quoted curly '{'something'}' and this is <<not>> end"; 
System.out.println(input.replaceAll("(?<!')\\{(.*?)\\}(?!')", "<<$1>>") 
         .equals(output)); 

打印

true 
+0

+1,感謝您指出我的(現已刪除)答案中的缺陷。 – jlordo

+0

非常感謝,這很有幫助 –

+0

對不起,大家,無法對答案投票(說...沒有足夠的聲譽)。對「這篇文章對你有用嗎?」回答「是」。題。 –

1

使用負Java Pattern文檔的the special constructs section的前瞻/後視結構。

+2

一個「簡單」的方法是使用捕獲組和反向引用在替換字符串。 – nhahtdh

+0

@nhahtdh是的,但我不會說更簡單,我會把它稱爲更混亂。如果可能的話,我喜歡將所有模式匹配放入模式中,而不是放入處理邏輯中。 –

+0

這是「更簡單」(引用),因爲它可能不適用於每個人。當然,我個人會使用環視。 – nhahtdh

0

嘗試這種情況:

String regex = "([^'])([{}])"; 
    Pattern pattern = Pattern.compile(regex); 
    Matcher matcher = pattern.matcher(str); 

    while (matcher.find()) { 
     if ("{".equals(matcher.group(2))) { 
      matcher.appendReplacement(strBuffer, matcher.group(1) + "<<"); 
     } else if ("}".equals(matcher.group(2))) { 
      matcher.appendReplacement(strBuffer,matcher.group(1) + ">>"); 
     } 
    } 
    matcher.appendTail(strBuffer); 
+0

只需更正您自己的代碼。 :) –

+0

謝謝你的更正。我試了幾次正則表達式失敗,但這很好。 :) –

+0

你應該接受我的答案,如果它爲你工作。 :/ –