Home > database >  Regular Expression how to stop at first match
Regular Expression how to stop at first match

Time:09-07

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 Demo

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 text AVVIDI
  • Related