Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regular Expression how to stop at first match

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)); 
}

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading