2013-04-16 60 views
0

我想查找替換部分的匹配項。Java替換匹配器

實施例:

this is awesome look at this two letter words get replaced 

返回將是

this <h1>is</h1> awesome look <h1>at</h1> this two letter words get replaced 

通知如何isat其將匹配正則表達式\b\w\w\b將被匹配被替換。

這是我正在處理的代碼。它還沒有完成,但我只是有點困惑,想知道是否有更簡單的方法。我正在搜索字符串並找到匹配。然後我將它添加到一個ArrayList並替換每個。問題是,我更換是{的事情之一,我想{{}

現在取代它的外觀,這將不斷地更換支架,因爲我不斷加入他們... 所以我的其他想法是用char替換它們,然後添加到一個新的StringBuilder對象中?

ArrayList<String> replacements = new ArrayList<String>(); 

String s = "::"; 

s += command; 

Pattern p = Pattern.compile("[!-~]"); 
Matcher match = p.matcher(this.execution); 

while(match.find()) 
{ 
    replacements.add(match.group()); 
} 

StringBuilder string = new StringBuilder(); 

for(int i=0; i<this.execution.length(); i++) 
{ 
    String a =new String(execution.charAt(i)); 
    if() 
    { 
    } 
} 
s += "::" + this.execution; 

回答

1

我真的不明白怎麼會你的代碼解決您上面所解釋的要求...

這就是說,它似乎是用做這種工作的一個更簡單的方法JAVA的replaceAll方法,通常用於兩個字母的單詞:

"this is awesome look at this two letter words get replaced" 
.replaceAll("(\\b\\w{2}\\b)", "<h1>$1</h1>"); 

此打印:

this <h1>is</h1> awesome look <h1>at</h1> this two letter words get replaced 
+0

酵母不是最聰明的舉動。我正在寫它爲其他東西。我需要檢查每個字符以確保它不是某個字符,然後將其替換。所以我將它添加到字符串生成器中,同時將它建立起來。 –