猿问

正则表达式只搜索一位数

我试图找到只有一位数字的句子。


sentence="I'm 30 years old."

print(re.match("[0-9]", sentence)

然后它返回


<re.Match object; span=(0, 1), match='3'>

但它是 30,实际上是两位数,我不希望它匹配。似乎每个由 3 和 0 组成的数字都被认为是一个独立的数字。这些数字是我国家通常使用的两字节数字。


如何更改我的正则表达式?谢谢!


吃鸡游戏
浏览 405回答 4
4回答

达令说

改用这个模式(它寻找个位数):import reprint(re.search(r'\b\d\b', "I'm 30 years old."))输出:None这也适用于 Python 3 中的 Unicode 字符。要考虑标点符号,您可以使用 \b\d(\b|\.|\?|\!)

拉莫斯之舞

您应该添加负后视和负前瞻以避免在独立数字前后出现数字:re.findall("(?<!\d)\d(?!\d)", "200 20 1 20 200 20 2")#['1', '2']re.findall("(?<!\d)\d(?!\d)", "200 20 20 200 20")#[]if not re.findall("(?<!\d)\d(?!\d)", "200 20 20 200 20"):&nbsp; &nbsp; print("no single-digit numbers")else:&nbsp; &nbsp; print("some single-digit numbers")

ITMISS

您的问题有点不清楚,但我的理解是,您只想匹配只有一位数字的句子,这些句子可能会在句子中重复多次,但在任何特定事件中不应超过一位数字。喜欢,我今年 30 岁。(这不应该匹配,因为它有 30 个多于一位的数字)我 3 岁。(这应该匹配,因为它只有 3 个数字)我3岁,你30岁。(这不应该匹配,因为它有 3 和 30,其中 30 是多位数)我3岁,你5岁。(这应该匹配,因为它有 3 和 5 这只是一位数字)我是个好男孩。(这不匹配,因为它根本没有任何数字)让我知道这是否是您想要的。如果是,你可以使用这个正则表达式,^(?!.*\d\d)(?=.*\d).*$解释:^&nbsp;--> 字符串开头(?!.*\d\d)&nbsp;--> 一个负面的前瞻,确保句子不包含任何多位数。(?!.*\d\d)&nbsp;--> 一个负面的前瞻,确保句子不包含任何多位数。.*&nbsp;--> 匹配任何文本$&nbsp;--> 字符串结束这是示例python代码,arr= ["I'm 30 years old.","I'm 3 years old.", "I'm 3 years and you are 30 years old.", "I'm 3 years and you are 5 years old.", "I am a good boy."]for s in arr:&nbsp; &nbsp; if re.search("^(?!.*\d\d)(?=.*\d).*$", s):&nbsp; &nbsp; &nbsp; &nbsp; print(s+' --> Sentence has only one digit')&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; print(s+' --> Sentence has either no digit or more than one digit')哪些输出,I'm 30 years old. --> Sentence has either no digit or more than one digitI'm 3 years old. --> Sentence has only one digitI'm 3 years and you are 30 years old. --> Sentence has either no digit or more than one digitI'm 3 years and you are 5 years old. --> Sentence has only one digitI am a good boy. --> Sentence has either no digit or more than one digit

斯蒂芬大帝

我们可以尝试使用re.search以下模式:(?=.*\d.*\d).*这是一个积极的前瞻,如果两个(或更多)数字出现在字符串中的任何位置,则为真。具体来说,我们不希望此模式匹配,以验证您的输入。sentence="I'm 30 years old."if not re.search("(?=.*\d.*\d).*", sentence):&nbsp; &nbsp; print 'match'else:&nbsp; &nbsp; print 'no match'
随时随地看视频慕课网APP

相关分类

Python
我要回答