问题
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