[英]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.