The question is published on by Tutorial Guruji team.
hope this is a reasonable way to try explain my goal.
My goal is to update strings from
"unchanged DETECT_OPEN blah DETECT_CLOSE unchanged"
to
"unchanged UPDATED_OPEN blah UPDATED_CLOSE unchanged"
So for
DETECT_OPEN = [ DETECT_CLOSE = ] UPDATED_OPEN = < UPDATED_CLOSE = >
on an input string of
"this stays the same [i am wrapped] nothing to do here"
after processing it is
"this stays the same <i am wrapped> nothing to do here"
Is there a good way to tackle this with regex? I’m in java; so a java specific example would be ideal; but any regex is welcome; I’ll be happy to try take it from there.
Not sure if it’ll make any difference; but the OPEN and CLOSE markers can be more than 1 character; and not equal in length.
So for example
DETECT_OPEN = || DETECT_CLOSE = |
Simple example:
"this stays the same ||i am wrapped| nothing to do here"
And the reason I can’t use multiple find replaces – is for scenarios like
"this isn't an open || because it doesn't close. This open || is closed |, this close | was never opened"
So after processing it would be
"this isn't an open || because it doesn't close. This open < is closed >, this close | was never opened"
Thanks, Brent
Answer
You can do this using a capture group:
String replaced = input.replaceAll("\[(.*?)\]", "<$1>");
This creates a new string, with the [...]
replaced with <...>
.
The $1
refers to the expression that was captured within the first matched (...)
in the pattern.