为了账号安全,请及时绑定邮箱和手机立即绑定

正则表达式只搜索一位数

正则表达式只搜索一位数

吃鸡游戏 2021-09-01 14:08:49
我试图找到只有一位数字的句子。sentence="I'm 30 years old."print(re.match("[0-9]", sentence)然后它返回<re.Match object; span=(0, 1), match='3'>但它是 30,实际上是两位数,我不希望它匹配。似乎每个由 3 和 0 组成的数字都被认为是一个独立的数字。这些数字是我国家通常使用的两字节数字。如何更改我的正则表达式?谢谢!
查看完整描述

4 回答

?
达令说

TA贡献1821条经验 获得超6个赞

改用这个模式(它寻找个位数):


import re

print(re.search(r'\b\d\b', "I'm 30 years old."))

输出:


None

这也适用于 Python 3 中的 Unicode 字符。要考虑标点符号,您可以使用 \b\d(\b|\.|\?|\!)


查看完整回答
反对 回复 2021-09-01
?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

您应该添加负后视和负前瞻以避免在独立数字前后出现数字:


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"):

    print("no single-digit numbers")

else:

    print("some single-digit numbers")


查看完整回答
反对 回复 2021-09-01
?
ITMISS

TA贡献1871条经验 获得超8个赞

您的问题有点不清楚,但我的理解是,您只想匹配只有一位数字的句子,这些句子可能会在句子中重复多次,但在任何特定事件中不应超过一位数字。喜欢,

  1. 我今年 30 岁。(这不应该匹配,因为它有 30 个多于一位的数字)

  2. 我 3 岁。(这应该匹配,因为它只有 3 个数字)

  3. 我3岁,你30岁。(这不应该匹配,因为它有 3 和 30,其中 30 是多位数)

  4. 我3岁,你5岁。(这应该匹配,因为它有 3 和 5 这只是一位数字)

  5. 我是个好男孩。(这不匹配,因为它根本没有任何数字)

让我知道这是否是您想要的。如果是,你可以使用这个正则表达式,

^(?!.*\d\d)(?=.*\d).*$

解释:

  • ^ --> 字符串开头

  • (?!.*\d\d) --> 一个负面的前瞻,确保句子不包含任何多位数。

  • (?!.*\d\d) --> 一个负面的前瞻,确保句子不包含任何多位数。

  • .* --> 匹配任何文本

  • $ --> 字符串结束

这是示例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:

    if re.search("^(?!.*\d\d)(?=.*\d).*$", s):

        print(s+' --> Sentence has only one digit')

    else:

        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 digit

I'm 3 years old. --> Sentence has only one digit

I'm 3 years and you are 30 years old. --> Sentence has either no digit or more than one digit

I'm 3 years and you are 5 years old. --> Sentence has only one digit

I am a good boy. --> Sentence has either no digit or more than one digit


查看完整回答
反对 回复 2021-09-01
?
斯蒂芬大帝

TA贡献1827条经验 获得超8个赞

我们可以尝试使用re.search以下模式:


(?=.*\d.*\d).*

这是一个积极的前瞻,如果两个(或更多)数字出现在字符串中的任何位置,则为真。具体来说,我们不希望此模式匹配,以验证您的输入。


sentence="I'm 30 years old."

if not re.search("(?=.*\d.*\d).*", sentence):

    print 'match'

else:

    print 'no match'


查看完整回答
反对 回复 2021-09-01
  • 4 回答
  • 0 关注
  • 404 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号