Python 仅用于字符串中的数字的正则表达式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50177113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:24:37  来源:igfitidea点击:

regex for only numbers in string?

pythonregexintegermatchwhitespace

提问by Yann Droy

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:

我找不到只包含空格或整数的字符串的正则表达式。该字符串是用户在键盘上的输入。它可以包含所有内容,但\n(但我猜这无关紧要),但我们可以专注于 ASCII,因为它应该是英语句子 这里有一些例子:

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.

但我无法获得正则表达式。我的正则表达式目前是,re.match(r'(\b\d+\b)+', text)但它不起作用。

回答by Mark

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

需要将开始(^)和行尾($)字符放入,否则字符串中包含字符的部分会匹配,导致误报匹配

回答by bobble bubble

How about something like this

这样的事情怎么样

^ *\d[\d ]*$

See demo at regex101

在 regex101 上查看演示

The pattern requires at least one digit to be contained.

该模式需要至少包含一位数字。

回答by The fourth bird

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

要仅匹配空格或数字,您可以使用:

^[ 0-9]+$

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

这将从字符串的开头匹配^一个或多个空格或使用字符类的数字,[ 0-9]+直到字符串的结尾$