我需要检查给定的字符串是否以正则表达式字符串结尾。我写了下面的代码:
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
罐头可以带数字或不带数字结束。这是一个好方法吗?
由于$
锚点已经确保模式必须在末尾匹配,因此简单find
就足够了;您无需验证比赛结束。如果您将样式放在前面,则.*
可以使用matches
而不是find
来删除整个样板:
boolean endsWith="wf-008-dam-mv1".matches(".*mv(\\d)?$");
System.out.println("Ends with "+endsWith);
这就是您所需要的...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句