Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex Python正则表达式匹配元组对_Regex_Python 2.7 - Fatal编程技术网

Regex Python正则表达式匹配元组对

Regex Python正则表达式匹配元组对,regex,python-2.7,Regex,Python 2.7,正在查找正则表达式以匹配列表中的元组对。一直在使用下面的正则表达式 s = '[(aleakedteaserand, NN), (abehind, IN), (the, DT)]' re.findall(r'\((.*,.*)\)',s) 但它仍然缺少末端支架 ['aleakedteaserand, NN), (abehind, IN), (the, DT'] 预期产出: [(阿莱克德泰斯兰,NN),(阿贝辛德,IN),(阿莱克德泰斯兰)] 你没有把RegEx变成ungreedy。解

正在查找正则表达式以匹配列表中的元组对。一直在使用下面的正则表达式

s = '[(aleakedteaserand, NN), (abehind, IN), (the, DT)]'    
re.findall(r'\((.*,.*)\)',s)
但它仍然缺少末端支架

['aleakedteaserand, NN), (abehind, IN), (the, DT']
预期产出:

[(阿莱克德泰斯兰,NN),(阿贝辛德,IN),(阿莱克德泰斯兰)]


你没有把RegEx变成ungreedy。解决方案是
re.findall(r'\(.*?,.*?)\),s)

备选方案。第一种方法使用补码匹配,在不可用的情况下,补码匹配通常用作非贪婪搜索的替代方法

>>> re.findall(r'\(([^)]*)\)',s)
['aleakedteaserand, NN', 'abehind, IN', 'the, DT']

>>> re.split('\), \(', s.strip('[()]'))
['aleakedteaserand, NN', 'abehind, IN', 'the, DT']
没有正则表达式

>>> s.strip('[()]').split('), (')
['aleakedteaserand, NN', 'abehind, IN', 'the, DT']

要获得问题中提到的预期输出,请将转义的
移到括号内:
re.findall(r'(\(.*?,.*)),s)
@Wray.No.OP希望匹配但不捕获参数。@Wray。预期输出中的括号和括号是芬德尔在这种情况下返回的元组列表。请在预期输出中加上正确的引号。