Java替换匹配的正则表达式[重复]

问题描述 投票:0回答:1

抱歉,我不得不重新写这个问题,我正在完成它,有人关闭了它。 他们没有好心地解释为什么我不得不重新发布? 请告诉我什么是令人困惑的。

要点:我想用部分匹配替换正则表达式匹配 所以如果我正则表达式 hi 我希望它被替换为 {hi} 如果正则表达式匹配 at 我想替换为 {at}

这太棒了,看看这两个字母的单词被替换了 回报将是

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

注意 is 和 at which 将如何匹配正则表达式 \w\w 将被匹配替换

这是我正在编写的代码...不要判断它还没有完成,但我只是有点困惑,想知道是否有更简单的方法。我搜索字符串并找到匹配项,然后将其放入数组列表并替换每个字符串。问题是我要替换的内容之一是 { 并且我想将其替换为 {{} 现在一看,这将不断替换括号,因为我不断添加它们......所以我的另一个想法是逐个字符替换它们并添加到新的

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;
java regex replaceall
1个回答
5
投票

尝试

str = str.replaceAll("(\\b\\w\\w\\b)", "<h1>$1</h1>");
© www.soinside.com 2019 - 2024. All rights reserved.