pattern.matcher() vs pattern.matches()

前端 未结 8 1903
时光说笑
时光说笑 2020-11-30 06:03

I am wondering why the results of the java regex pattern.matcher() and pattern.matches() differ when provided the same regular expression and same string

         


        
8条回答
  •  攒了一身酷
    2020-11-30 06:13

    I think your question should really be "When should I use the Pattern.matches() method?", and the answer is "Never." Were you expecting it to return an array of the matched substrings, like .NET's Matches methods do? That's a perfectly reasonable expectation, but no, Java has nothing like that.

    If you just want to do a quick-and-dirty match, adorn the regex with .* at either end, and use the string's own matches() method:

    System.out.println(str.matches(".*\\+.*"));
    

    If you want to extract multiple matches, or access information about a match afterward, create a Matcher instance and use its methods, like you did in your question. Pattern.matches() is nothing but a wasted opportunity.

提交回复
热议问题