[英]Good way to check if a String ends with a Regex String
我需要检查给定的字符串是否以正则表达式字符串结尾。 我写了以下代码:
public static void main(String[] args) {
String str = "wf-008-dam-mv1";
String regex = "mv(\\d)?$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
if(matcher.find() && matcher.end() == str.length()) {
System.out.println("Ends with true");
} else {
System.out.println("Ends with false");
}
}
在这里, str
可以以数字结尾或不以数字结尾。 这是一个好方法吗?
这是一个相当合理的方法,除了matcher.end() == str.length()
检查是多余的。 $
regex锚已经可以解决这个问题。
由于$
锚已经确保模式必须在末尾匹配,因此简单find
就足够了; 您无需验证比赛结束。 如果在样式前面加上.*
,则可以使用matches
而不是使用find
来删除整个样板:
boolean endsWith="wf-008-dam-mv1".matches(".*mv(\\d)?$");
System.out.println("Ends with "+endsWith);
这就是您所需要的...
matcher.find()
为您完成工作,无需与matcher.end() == str.length()
进行检查
API说
If the match succeeds then more information can be obtained via the start, end, and group methods
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.