Regex to test if a string ends with a number

后端 未结 5 1419
梦谈多话
梦谈多话 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条回答
  • 2021-01-11 11:04

    Your RegEx expression is slightly off. Try this:

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

    You can also simply test like this if you are evaluating a line at a time:

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

    Your original expression, without .* only tested to see whether the string was a number and did not account for text that may precede that number. That's why it was always false.

    The following does evaluate to true:

    System.out.println("4".matches("^\\d$"));
    
    0 讨论(0)
  • 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$"));
    
    0 讨论(0)
  • 2021-01-11 11:24

    Your regex will not match the entire string but only the last part. Try the below code and it should work fine as it matches the entire string.

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

    You can test this for a quick check on online regex testers like this one: http://www.regexplanet.com/simple/index.html. This also gives you what you should use in the Java code in the results with appropriate escapes.

    The .+ will ensure that there is atleast one character before the digit. The ? will ensure it does a lazy match instead of a greedy match.

    0 讨论(0)
  • 2021-01-11 11:24
    System.out.println("I end with a number 4".matches(".*\\d")); // prints true
    

    or

    String s = "I end with a number 4";
    System.out.println(Character.isDigit(s.charAt(s.length()-1)));  // prints true
    
    0 讨论(0)
  • 2021-01-11 11:28

    try this:

    System.out.println("I end with a number 4".matches(".*\\d\$"));
    
    0 讨论(0)
提交回复
热议问题