Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to test if a string ends with a number

Tags:

java

regex

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$"));
like image 709
Thor Avatar asked Oct 07 '11 16:10

Thor


People also ask

How do you check if a string is a number regex?

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.

What is the regex pattern for end of 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.

What does '$' mean in regex?

$ 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.

How do you check if a string ends with a number in python regex?

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.


2 Answers

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$"));
like image 148
Sean Patrick Floyd Avatar answered Oct 13 '22 12:10

Sean Patrick Floyd


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.

like image 45
Kash Avatar answered Oct 13 '22 13:10

Kash