2012-06-02 123 views
5

我有一個很長的字符串。我想用匹配的正則表達式(組)的一部分替換所有的匹配。替換字符串的部分匹配正則表達式

例如:

String = "This is a great day, is it not? If there is something, THIS IS it. <b>is</b>". 

我想,以取代所有的話"is",讓我們說,"<h1>is</h1>"。案件應保持原來的一致。所以,最終的字符串我想要的是:

This <h1>is</h1> a great day, <h1>is</h1> it not? If there <h1>is</h1> something, 
THIS <h1>IS</h1> it. <b><h1>is</h1></b>. 

正則表達式我嘗試:

Pattern pattern = Pattern.compile("[.>, ](is)[.<, ]", Pattern.CASE_INSENSITIVE); 
+2

當您嘗試它時,發生了什麼事? –

+0

模式很好。我不明白的是如何更換。 – varunl

回答

8

Matcher類通常與Pattern結合使用。使用Matcher.replaceAll()方法替換所有匹配字符串

String str = "This is a great day..."; 
Pattern p = Pattern.compile("\\bis\\b", Pattern.CASE_INSENSITIVE); 
Matcher m = p.matcher(str); 
String result = m.replaceAll("<h1>is</h1>"); 

注意的:使用正則表達式\b命令將匹配一個單詞邊界(如空格)上。這是有用的,以確保只有單詞「是」匹配,而不是包含字母「我」和「S」(如「島」)的單詞。

4

像這樣:

str = str.replaceAll(yourRegex, "<h1>$1</h1>"); 

$1是指由組#1中捕獲的文本你的正則表達式。

+0

該解決方案的缺點是它始終是區分大小寫的。沒有辦法將正則表達式定義爲不區分大小寫。 – Michael

+2

@Michael - 如果你需要不區分大小寫,只需在正則表達式的開頭加入一個'(?i)'修飾符。 –

+0

哦,不知道。忽略我的評論。 ( – Michael

0

只需使用反向引用即可。

"This is a great day, is it not? If there is something, THIS IS it. <b>is</b>".replaceAll("[.>, ](is)[.<, ]", "<h1>$2</h1>");應該做的。

+0

)再說一遍,你不能說正則表達式對這個解決方案是不區分大小寫的。 – Michael

+0

沒關係,你可以用'(?i)'預先給定正則表達式字符串,以使它不區分大小寫。 – Michael

3

邁克爾的回答是好,但如果你碰巧專門只想[.>, ][.<, ]爲界限,你可以做這樣的:

String input = "This is a great day, is it not? If there is something, THIS IS it. <b>is</b>"; 
Pattern p = Pattern.compile("(?<=[.>, ])(is)(?=[.<, ])", Pattern.CASE_INSENSITIVE); 
Matcher m = p.matcher(input); 
String result = m.replaceAll("<h1>$1</h1>"); 
1
yourStr.replaceAll("(?i)([.>, ])(is)([.<, ])","$1<h1>$2</h1>$3") 

(?i)指示忽略大小寫;用括號將所有想要重複使用的東西包裝起來,以$ 1 $ 2和$ 3的形式重新使用它們,將它們連接成你想要的。

0

它可能是一個晚此外,但如果有人正在尋找這個喜歡
搜索「東西」也是他需要「東西」也被視爲結果,

模式P = Pattern.compile(「([^] )是([^ \。])」);
String result = m.replaceAll(「< \ h1> $ 1is $ 2 </h1>」);

將導致< \ h1>某事</h1>太

相關問題