Regex to test if a string ends with a number

后端 未结 5 1514
梦谈多话
梦谈多话 2021-01-11 10:28

I\'d like to test if a string ends with a a digit. I expect the following Java line to print true. Why does it print false?

System.out.println(\"I end with         


        
5条回答
  •  萌比男神i
    2021-01-11 11:24

    In Java Regex, there's a difference between Matcher.find() (find a match anywhere in the String) and Matcher.matches() (match the entire String).

    String only has a matches() method (implemented equivalent to this code:Pattern.compile(pattern).matcher(this).matches();), so you need to create a pattern that matches the full String:

    System.out.println("I end with a number 4".matches("^.*\\d$"));
    

提交回复
热议问题