正则表达式仅适用于字符串中的数字? [英] regex for only numbers in string?

查看:85
本文介绍了正则表达式仅适用于字符串中的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到仅包含空格或整数的字符串的正则表达式. 该字符串是用户在键盘上的输入.它可以包含除\n之外的所有内容(但我想没关系),但是我们可以专注于ASCII,因为它应该是英文句子 以下是一些示例:

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:

确定:

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

不行:

'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)]

但是我无法获取正则表达式.我的正则表达式当前为re.match(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'^([\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

这篇关于正则表达式仅适用于字符串中的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆