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$"));
To check if a string contains only numbers in JavaScript, call the test() method on this regular expression: ^\d+$ . The test() method will return true if the string contains only numbers. Otherwise, it will return false . The RegExp test() method searches for a match between a regular expression and a string.
The correct regex to use is ^\d+$. Because “start of string” must be matched before the match of \d+, and “end of string” must be matched right after it, the entire string must consist of digits for ^\d+$ to be able to match.
$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.
To check if a string ends with a number:Call the str. isdigit() method on the character. If the method returns True , the string ends with a number.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With