2014-09-03 87 views
1

我需要检查给定的字符串是否以正则表达式字符串结尾。我写了下面的代码:好的方法来检查一个字符串是否以正则表达式字符串结尾

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可以结尾有或没有数字。这是做这件事的好方法吗?

回答

2

由于$锚已经确保了图案必须在最后匹配,简单find足够;你不需要验证比赛结束。如果你在前面加上.*你的模式,你可以使用matches,而不是find它允许你删除整个样板:

boolean endsWith="wf-008-dam-mv1".matches(".*mv(\\d)?$"); 
System.out.println("Ends with "+endsWith); 

这就是你所需要的...

4

这是一个非常合理的方式来做到这一点,除了matcher.end() == str.length()检查是多余的。 $正则表达式的锚已经照顾到了这一点。

1

matcher.find()做这项工作给你,也不需要检查与matcher.end() == str.length()

API

If the match succeeds then more information can be obtained via the start, end, and group methods 
相关问题