Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.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
Python re.findall非贪婪结果_Python_Regex_Findall_Non Greedy - Fatal编程技术网

Python re.findall非贪婪结果

Python re.findall非贪婪结果,python,regex,findall,non-greedy,Python,Regex,Findall,Non Greedy,我正在尝试仅获取具有以下代码的“Text3”部分: import re stringtotest = "begin:Text1<wrong>Text2<wrong>Text3<right>Text4<wrong>" right = re.findall("<wrong>(.+?)<right>",stringtotest) >>> right ['Text2<wrong>Text3'] 重新导

我正在尝试仅获取具有以下代码的“Text3”部分:

import re
stringtotest = "begin:Text1<wrong>Text2<wrong>Text3<right>Text4<wrong>"
right = re.findall("<wrong>(.+?)<right>",stringtotest)
>>> right
['Text2<wrong>Text3']
重新导入
stringtotest=“开始:Text1Text2Text3Text4”
右=关于findall(“(.+?”,stringtotest)
>>>对
['Text2Text3']

为什么Python也给我Text2?如何告诉他我想要的只是最接近的“错”后面的部分?多谢各位

匹配任何内容。可以使用否定字符类来限制匹配:

<wrong>([^<]+?)<right>
([^
((?:(?!))*))
您可以使用一个基于否定的前瞻量词。请参阅演示


这个问题与贪婪与非贪婪没有多大关系,因为即使是非贪婪匹配也无法产生期望的结果。询问者使用的是惰性匹配,这更不具攻击性。你完全正确。对不起,我是Python新手。如果我有stringtotest=“开始\r\nText1\r\n\r\nText2\r\n更多文本\r\n\r\nText3\r\n\r\nText4\r\n”我如何才能只获取之前的零件?您不应该在此处使用惰性匹配,因为贪婪匹配永远不会超出此处的“右”边界“。贪婪地说,在关闭
和打开
之间匹配字符需要一步。你说得对,我本来打算编辑它,但我认为保存20步对询问者来说并不重要。不过,对于其他观众来说,这是一个很好的信息,谢谢你的评论。”。
(?<=<wrong>)([^<]+?)(?=<right>)
<wrong>((?:(?!<wrong>).)*)<right>