1

Sorry i had to re write this question i was in the middle of finishing it and someone closed it. they weren't kind enough to explain why so i had to repost? please inform me what is confusing.

Main point: I want to replace a regex match with part of the match so if i regex hi i want it to be replaced with {hi} if regex match at i want to replace with {at}

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 a replaced

this is the code i was working on... don't judge it's not finished but i am just a little confused and wondering if there is an easier way. i was search the string and finding the matches and then i was going to go 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

5

try

str = str.replaceAll("(\\b\\w\\w\\b)", "<h1>$1</h1>");
Sign up to request clarification or add additional context in comments.

4 Comments

does $1 mean the current match? thank you for taking the time
$1 means group #1 in current match. group is the expr in round brackets
so i would have to do $1, $2 ..etc for each match then?
oooh i get it. I was so confused on what a group is. thank you so much get it to work

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.