My regex pattern looks like this:
(?<=_)(.*?)(?=_)
I want replace only the first match between the two underscores (its not allways AVVI, it can be different. Same as AVVIDI):
T_AVVI_EINZELPOSTEN_TEST -> T_AVVIDI_EINZELPOSTEN_TEST
My regex pattern matches AVVI and EINZEPLOSTEN. How can i modify my regex to find only the first match AVVI?
code:
private Identifier addPrefix(final Identifier identifier) {
if (isExcluded(identifier)) {
return identifier;
}
Pattern p = Pattern.compile("(?<=_)(.*?)(?=_)");
Matcher m = p.matcher(identifier.getText());
return Identifier.toIdentifier(m.replaceAll(prefix));
}
CodePudding user response:
You can do this using .replaceFirst
like this using start anchor and a capture group:
String line = identifier.getText()
.repalceFirst("^([^_]*_)[^_]*(?=_)", "$1AVVIDI");
RegEx Breakup:
^
: Start([^_]*_)
: Capture group #1 to match 0 or more chars that are not_
followed by a_
[^_]*
: Match 0 or more chars that are not_
(?=_)
: Positive lookahead to assert presence of_
at next position$1AVVIDI
: to replace with value in capture group #1 followed by textAVVIDI