[英]Good way to check if a String ends with a Regex String
I need to check if a given String ends with a Regular Expression String. 我需要检查给定的字符串是否以正则表达式字符串结尾。 I have written the following code:
我写了以下代码:
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");
}
}
Here the str
can ends with or without number. 在这里,
str
可以以数字结尾或不以数字结尾。 Is it a good way to do it? 这是一个好方法吗?
That's a pretty reasonable way to do it, except that the matcher.end() == str.length()
check is redundant. 这是一个相当合理的方法,除了
matcher.end() == str.length()
检查是多余的。 The $
regex anchor already takes care of that. $
regex锚已经可以解决这个问题。
Since the $
anchor already ensures that the pattern must match at the end, a simple find
is enough; 由于
$
锚已经确保模式必须在末尾匹配,因此简单find
就足够了; you don't need to verify the end of the match. 您无需验证比赛结束。 If you prepend your pattern with
.*
you can use matches
rather than find
which allows you to remove the entire boilerplate: 如果在样式前面加上
.*
,则可以使用matches
而不是使用find
来删除整个样板:
boolean endsWith="wf-008-dam-mv1".matches(".*mv(\\d)?$");
System.out.println("Ends with "+endsWith);
That's all you need… 这就是您所需要的...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.