Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to find a number in a string

Tags:

regex

I've got a string that may or may not contain a number of 4 or 5 digits. I'm looking for a regex that can detect if the string does in fact have such a number.

like image 886
Jon Dewees Avatar asked Apr 03 '09 13:04

Jon Dewees


People also ask

How do you find a number in a string?

To find numbers from a given string in Python we can easily apply the isdigit() method. In Python the isdigit() method returns True if all the digit characters contain in the input string and this function extracts the digits from the string. If no character is a digit in the given string then it will return False.

How do I find a number in regex?

Python Regex – Get List of all Numbers from String. To get the list of all numbers in a String, use the regular expression '[0-9]+' with re. findall() method. [0-9] represents a regular expression to match a single digit in the string.

How do I find a character in a string in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What does ?= Mean in regex?

?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).


1 Answers

The foolproof one to avoid longer numbers would be:

([^\d]|^)\d{4,5}([^\d]|$) 

I'm assuming you don't want to allow for a comma after the thousands digit? If you do then:

([^\d]|^)\d{1,2},\d{3}([^\d]|$) 
like image 163
David M Avatar answered Oct 18 '22 07:10

David M