python上的正则表达式只选择一位数字

问题描述 投票:2回答:2

我希望只挑选一位数的号码。 在windows python上,使用日语unicode,我:

s = "17 1 27歳女1"
re.findall(r'[1-7]\b', s)

我需要匹配1中的第二个1和最后一个s - 而不是17最初的1。 期望的输出:

['1', '1'] 
python regex
2个回答
2
投票

这是你正在寻找的正则表达式:

(?<!\d)[1-7](?!\d)

测试:

import re
s="17 1 27歳女1"
re.findall(r'(?<!\d)[1-7](?!\d)', s)

输出:

['1', '1']

3
投票

尝试使用negative-lookbehind (?<!\d)。这将忽略数字前面有另一个数字的匹配,即:

import re

s = "17 1 27歳女1"
x = re.findall(r"(?<!\d)[1-7]\b", s)
print(x)
# ['1', '1']

Regex Demo Python Demo


正则表达式说明:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.