正则表达式即使它们分开也能找到重复的数字

Jad*_*win 0 python regex

我正在尝试创建一个正则表达式,它会告诉我一个字符串中是否有两个或多个重复数字,以逗号分隔。例如“10,2,3,4,5,6,7,8,9,10”将返回真,因为有两个十。

我想我很接近。到目前为止,我有:

if re.match(r"(\d+),.+\1",line):
Run Code Online (Sandbox Code Playgroud)

谢谢!

Nic*_*ick 5

您不需要为此使用正则表达式。只需使用 转换为列表split,然后将其转换为一个集合(它将只包含列表中的唯一数字)并比较长度:

line = "10,2,3,4,5,6,7,8,9,10"

lst = line.split(',')
unq = set(lst)
if (len(lst) != len(unq)):
    # non-unique numbers present
Run Code Online (Sandbox Code Playgroud)

如果你想使用正则表达式,你需要使用re.search,而不是re.match作为re.match需要比赛开始的字符串,这将排除匹配的开始2"1,2,3,4,5,6,2,7,8,9,10"。此外,您需要(\d+)用分词符 ( \b)包围您,这样1in"1,2,3,4,5,6,2,7,8,9,10"就不会与1in匹配10。这个正则表达式会给你你想要的结果:

m = re.search(r'\b(\d+)\b.*\b\1\b', line)
if m:
    print('Duplicate number ' + m.group(1))
Run Code Online (Sandbox Code Playgroud)