简体   繁体   English

正则表达式在最后一个下划线后查找给定数量的字符

[英]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 . 我正在使用[^_]*(?=\\.pdf) ,但它会找到下划线后的所有字符,例如AB12123321

I need to find the first two characters AB only. 我只需要找到前两个字符AB

Moreover, there is no way to access the code, I can only modify the regex pattern. 而且,没有办法访问代码,我只能修改regex模式。

If you want to solve the problem using a regex you may use: 如果要使用正则表达式解决问题,可以使用:

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

See regex demo . 参见regex演示

Details 细节

  • (?<=_) - an underscore must appear immediately to the left of the current position (?<=_) -下划线必须立即出现在当前位置的左侧
  • [^_]{2} - Capturing group 1: any 2 chars other than underscore [^_]{2} -捕获组1:下划线以外的任意2个字符
  • (?=[^_]*$) - immediately to the left of the current position, there must appear any 0+ chars other than underscore and then an end of string. (?=[^_]*$) -当前位置的左侧,必须出现除下划线以外的任何0+字符,然后是字符串的结尾。

See the Java demo : 参见Java演示

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 . 输出: AB

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 正则表达式查找第一个下划线之前和之后的所有字符,然后确保它们相同 - Regex to find all characters before and after first underscore, then make sure they are the same 查找仅包含给定字符的单词:RegEx - Find words only containing given characters : RegEx java正则表达式查找第一个和最后一个字符 - java regex find first and last characters 在点扩展之前的最后一个下划线之后查找字符串 - Find string after last underscore before dot extension 查找给定Word中字符的重复次数 - Find number of repetitions of characters in a given Word 正则表达式-对于精确的6个字符,前3个字符为静态字符,后3个为数字 - Regex- for exact 6 characters, first 3 characters are static and last 3 are number 使用正则表达式查找 Json 值:匹配字符串,然后是任意数量的字符,然后是第二个匹配字符串后的值 - Find Json values with Regex: Matching string, then any number of characters and then value after second matching string 正则表达式在最后一个冒号之后查找字符串 - Regex to find a string after the last colon 正则表达式(Java)查找所有以偶数个其他字符开头的字符 - Regex (Java) to find all characters preceded by an even number of other characters 如何在java中使用正则表达式查找字符串中最后一次出现的字符集? - How to find a last occurrence of set of characters in string using regex in java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM