Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex for only numbers in string?

I can't find the regex for strings containing only whitespaces or integers. The string is an input from user on keyboard. It can contain everything but \n (but it doesn't matter I guess), but we can focus on ASCII since it's supposed to be English sentences Here are some examples:

OK:

'1'
'2 3'
'   3 56 '
'8888888       333'
' 039'

not OK:

'a'
'4 e'
'874 1231 88 qqqq 99'
' shf ie sh f 8'

I have this which finds the numbers:

t = [int(i) for i in re.findall(r'\b\d+\b', text)]

But I can't get the regex. My regex is currently re.match(r'(\b\d+\b)+', text) but it doesn't work.

like image 878
Yann Droy Avatar asked May 04 '18 14:05

Yann Droy


People also ask

How do you use only numbers in regex?

To get a string contains only numbers (0-9) we use a regular expression (/^[0-9]+$/) which allows only numbers.

How do you get a number from a string 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 you check if the input contains only numbers?

Use the test() method to check if a string contains only digits, e.g. /^[0-9]+$/. test(str) . The test method will return true if the string contains only digits and false otherwise.

How do I allow only letters and numbers in regex?

You can use regular expressions to achieve this task. In order to verify that the string only contains letters, numbers, underscores and dashes, we can use the following regex: "^[A-Za-z0-9_-]*$".


2 Answers

>>> re.match(r'^([\s\d]+)$', text)

You need to put start (^) and end of line ($) characters in. Otherwise, the part of the string with the characters in will match, resulting in false positive matches

like image 148
Mark Avatar answered Sep 25 '22 02:09

Mark


How about something like this

^ *\d[\d ]*$

See demo at regex101

The pattern requires at least one digit to be contained.

like image 39
bobble bubble Avatar answered Sep 22 '22 02:09

bobble bubble