• Post Reply Bookmark Topic Watch Topic
  • New Topic

Using replace in regular Matcher  RSS feed

 
AnilPrakash Raju
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I need to search for a pattern in a string. I have done that using:
Pattern p = Pattern.compile(myPattern);
Matcher m = p.matcher(String);
boolean result= m.find();

while (result) {
System.out.println(m.group());
result4= m.find();
}

What i want to do is replace the first two characters of the each result with && and update it to the main string?

Any ideas about how i could go about doing this?

Thanks in advance

Anil
 
Campbell Ritchie
Marshal
Posts: 56581
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Along time since I used Java regular expressions, but I think you can get an index where the match is found.

Then try putting the String into a StringBuilder, deleting two characters at the "found" index, and inserting "&&" at the same point.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
matcher.start() and end() give you what you need. Here's a fragment of working code:
 
AnilPrakash Raju
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot guys.

 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!