regex for only numbers in string?

谁说我不能喝 提交于 2020-11-29 08:25:43

问题


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.


回答1:


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




回答2:


How about something like this

^ *\d[\d ]*$

See demo at regex101

The pattern requires at least one digit to be contained.




回答3:


To match only a whitespace or a digit you could use:

^[ 0-9]+$

That would match from the beginning of the string ^ one or more whitespaces or a digit using a character class [ 0-9]+ until the end of the string $.



来源:https://stackoverflow.com/questions/50177113/regex-for-only-numbers-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!