Alex Rivera | Logout

Regex to test if a string ends with a number

Asked 2011-10-07T16:45:33.887
15

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 a number 4".matches("\\d$"));
Edit
Report

2 Answers

2

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$"));
answered 2011-10-07T16:51:12.290
0
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
answered 2011-10-07T16:51:04.087

Your Answer