我想找到替换部分匹配的内容。
示例:
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
注意如何替换与正则表达式
is
匹配的 at
和 \b\w\w\b
被替换。
这是我正在编写的代码。它还没有完成,但我只是有点困惑,想知道是否有更简单的方法。我正在搜索字符串并找到匹配项。然后我将它添加到 ArrayList 中并替换每一个。问题是我要替换的东西之一是
{
,我想用 {{}
替换它
现在一看,这将不断替换括号,因为我不断添加它们...... 所以我的另一个想法是逐个字符替换它们并添加到新的 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;
我真的不明白你的代码如何解决你上面解释的要求......
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