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|\.|\?|\!)

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

TA贡献1871条经验 获得超8个赞
您的问题有点不清楚,但我的理解是,您只想匹配只有一位数字的句子,这些句子可能会在句子中重复多次,但在任何特定事件中不应超过一位数字。喜欢,
我今年 30 岁。(这不应该匹配,因为它有 30 个多于一位的数字)
我 3 岁。(这应该匹配,因为它只有 3 个数字)
我3岁,你30岁。(这不应该匹配,因为它有 3 和 30,其中 30 是多位数)
我3岁,你5岁。(这应该匹配,因为它有 3 和 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

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'
添加回答
举报