Regex to find a given number of characters after last underscore

988 views Asked by At

I need to find two characters after the last underscore in given filename.

Example string:

sample_filename_AB12123321.pdf

I am using [^_]*(?=\.pdf), but it finds all the characters after the underscore like AB12123321.

I need to find the first two characters AB only.

Moreover, there is no way to access the code, I can only modify the regex pattern.

1

There are 1 answers

2
Wiktor Stribiżew On BEST ANSWER

If you want to solve the problem using a regex you may use:

 (?<=_)[^_]{2}(?=[^_]*$)

See regex demo.

Details

  • (?<=_) - an underscore must appear immediately to the left of the current position
  • [^_]{2} - Capturing group 1: any 2 chars other than underscore
  • (?=[^_]*$) - immediately to the left of the current position, there must appear any 0+ chars other than underscore and then an end of string.

See the Java demo:

String s = "sample_filename_AB12123321.pdf";
Pattern pattern = Pattern.compile("(?<=_)[^_]{2}(?=[^_]*$)");
Matcher matcher = pattern.matcher(s);
if (matcher.find()){
    System.out.println(matcher.group(0)); 
} 

Output: AB.