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
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$"));
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$"));
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.
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
try this:
System.out.println("I end with a number 4".matches(".*\\d\$"));