wood burning stoves 2.0*
The moose likes Java in General and the fly likes Regex and replacing groups Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Regex and replacing groups" Watch "Regex and replacing groups" New topic

Regex and replacing groups

Tim Patton

Joined: Oct 17, 2006
Posts: 7
I'm trying to figure out how to replace just part of a match using the java regex classes (or some other set). Say I have a regex like this:


It will match strings like this: 4-3 100-5656 1-1

I would like to use string replace on the 2nd group, but I am not sure how.

If I use string.replace(matcher.group(2), ....) then it will not work correctly in the case of 1-1. I can't use backreferences in string.replace since the '-' isn't included in a group (other than 0). Is this possible with any regex api for java? I know I could include everything in a group, but for my real world usage that could get too complicated.
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
I can't tell what you're trying to do here. Replace with what? Can you show an example of what you want the result to look like?

"I'm not back." - Bill Harding, Twister
I agree. Here's the link: http://aspose.com/file-tools
subject: Regex and replacing groups
Similar Threads
String from JTextField
use regex to replace a substring
regular expressions on Strings
String "contains" equivalent - But should look for case-in-sensitive string
regex does not match but has group(0)