Java replace Matcher

落花浮王杯 提交于 2019-12-13 05:55:16

问题


I want to find replace part of what is matched.

Example:

this is awesome look at this two letter words get replaced

the return would be

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

Notice how the is and at which would match regex \b\w\w\b would be matched are replaced.

This is the code I was working on. It's not finished but I am just a little confused and wondering if there is an easier way. I was searching the string and finding the matches. Then I was adding it to an ArrayList and replace each one. The problem is one of the thing that I am replacing is { and I want to replace it with {{}

Now in a look this will continually replace the brackets because I keep adding them... So my other thought was to replace them all one by one char by char and add to a new StringBuilder object?

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:


I don't really get how could your code solve the requirements you explained above...

That said, it seems to be a easier way to do this kind of job by using the JAVA's replaceAll method, typically for the two-letter words:

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

This prints:

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


来源:https://stackoverflow.com/questions/16028688/java-replace-matcher

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!