简体   繁体   中英

Regex to find a given number of characters after last underscore

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM