python正则表达式捕获出现次数未知的模式
例如:python正则表达式捕获出现次数未知的模式,python,regex,Python,Regex,例如: import re FOO = """neighbors= {5 7 9 11 13 14 15 16 17 }""" COMPILE = re.compile('(neighbors\s*=\s*\{\s*(\d+\s*)+\})') match = re.findall(COMPILE, FOO) print match[0] 代码如下所示: 这将只捕获最后一组,即17。如果我想捕获这些组中的每一个,即。 5、7、9、?基本上,您不能使用一个单独的捕获组,后跟重复标记+或*来捕获任
import re
FOO = """neighbors= {5 7 9 11 13 14 15 16 17 }"""
COMPILE = re.compile('(neighbors\s*=\s*\{\s*(\d+\s*)+\})')
match = re.findall(COMPILE, FOO)
print match[0]
代码如下所示:
这将只捕获最后一组,即17。如果我想捕获这些组中的每一个,即。
5、7、9、?基本上,您不能使用一个单独的捕获组,后跟重复标记+或*来捕获任意数量的序列 也许您应该捕获整数序列,然后将其拆分,如下所示:
import re
FOO = """neighbors= {5 7 9 11 13 14 15 16 17 }"""
COMPILE = re.compile('(neighbors\s*=\s*\{\s*((\d+\s*)+)\})') # added a capturing group
match = re.findall(COMPILE, FOO)
print match[0][1].split()
import re
FOO = """neighbors= {5 7 9 11 13 14 15 16 17 }"""
COMPILE = re.compile('(neighbors\s*=\s*\{\s*((\d+\s*)+)\})')
match = re.match(COMPILE, FOO)
if match:
print match.group(2).split()
else:
print 'input does not match regex'
其中打印:
['5', '7', '9', '11', '13', '14', '15', '16', '17']
此外,也许您不需要findall,只需要匹配即可,如下所示:
import re
FOO = """neighbors= {5 7 9 11 13 14 15 16 17 }"""
COMPILE = re.compile('(neighbors\s*=\s*\{\s*((\d+\s*)+)\})') # added a capturing group
match = re.findall(COMPILE, FOO)
print match[0][1].split()
import re
FOO = """neighbors= {5 7 9 11 13 14 15 16 17 }"""
COMPILE = re.compile('(neighbors\s*=\s*\{\s*((\d+\s*)+)\})')
match = re.match(COMPILE, FOO)
if match:
print match.group(2).split()
else:
print 'input does not match regex'
您还可以查看以下类似问题的主要答案:
基本上,不能使用单个捕获组后跟重复标记+或*来捕获任意数量的序列 也许您应该捕获整数序列,然后将其拆分,如下所示:
import re
FOO = """neighbors= {5 7 9 11 13 14 15 16 17 }"""
COMPILE = re.compile('(neighbors\s*=\s*\{\s*((\d+\s*)+)\})') # added a capturing group
match = re.findall(COMPILE, FOO)
print match[0][1].split()
import re
FOO = """neighbors= {5 7 9 11 13 14 15 16 17 }"""
COMPILE = re.compile('(neighbors\s*=\s*\{\s*((\d+\s*)+)\})')
match = re.match(COMPILE, FOO)
if match:
print match.group(2).split()
else:
print 'input does not match regex'
其中打印:
['5', '7', '9', '11', '13', '14', '15', '16', '17']
此外,也许您不需要findall,只需要匹配即可,如下所示:
import re
FOO = """neighbors= {5 7 9 11 13 14 15 16 17 }"""
COMPILE = re.compile('(neighbors\s*=\s*\{\s*((\d+\s*)+)\})') # added a capturing group
match = re.findall(COMPILE, FOO)
print match[0][1].split()
import re
FOO = """neighbors= {5 7 9 11 13 14 15 16 17 }"""
COMPILE = re.compile('(neighbors\s*=\s*\{\s*((\d+\s*)+)\})')
match = re.match(COMPILE, FOO)
if match:
print match.group(2).split()
else:
print 'input does not match regex'
您还可以查看以下类似问题的主要答案:
我建议使用更简单的正则表达式来匹配所有数字,并将其与re.findall一起使用: 哪个输出
Out[5]: ['5', '7', '9', '11', '13', '14', '15', '16', '17']
我建议使用更简单的正则表达式来匹配所有数字,并将其与re.findall一起使用: 哪个输出
Out[5]: ['5', '7', '9', '11', '13', '14', '15', '16', '17']
如果不需要检查name={…}语法,则比我的更简单;如果不需要检查name={…}语法,则比我的更简单