0

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;
0

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

yea wasn't the smartest move. I was writing it for something else tho. I needed to check each char to make sure it wasn't a certain char then replace it. so i was adding it to the string builder while building it back up.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.