2013-04-16 61 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

酵母不是最聪明的举动。我正在写它为其他东西。我需要检查每个字符以确保它不是某个字符,然后将其替换。所以我将它添加到字符串生成器中,同时将它建立起来。 –