Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.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 如何以非贪婪的方式将文本与特定循环的正则表达式匹配_Python_Regex - Fatal编程技术网

Python 如何以非贪婪的方式将文本与特定循环的正则表达式匹配

Python 如何以非贪婪的方式将文本与特定循环的正则表达式匹配,python,regex,Python,Regex,使用正则表达式模式(Python): (?使用以下方法改进正则表达式模式: import re s = 'start< obj1 obj2 start< obj3 >end' m = re.search(r'(?<=start<)[^<]*?(?=>?end)', s) res = m.group().strip() if m else m print(res) # obj3 重新导入 s='start

使用正则表达式模式(Python):


(?使用以下方法改进正则表达式模式:

import re

s = 'start< obj1 obj2 start< obj3 >end'
m = re.search(r'(?<=start<)[^<]*?(?=>?end)', s)
res = m.group().strip() if m else m
print(res)    # obj3
重新导入
s='startend'
m=重新搜索(r’(?这个怎么样

r'start.*<(.*)>.*end'
r'start.*.*end'

在这种情况下,第一个
*
是如此贪婪,以至于匹配到最后一个
的所有内容。这也可以在不查找或查找的情况下完成:

s= "start< obj1 obj2 start< obj3 >end"
m=re.search(r"start<\s*([^<]*?)\s*>end",s)
>>> m[1]
>>> 'obj3'
s=“开始结束”

m=re.search(r“start”您可以在前面添加一个空格字符使其成为
(?您好,谢谢您的回复,原始字符串的答案很好,但是如果我们有
startend
(三
startOn侧注:-IMO
[^Hi,它能工作,谢谢。好的,还有@CodeManiac版本。我会试着玩一点来理解这个正则表达式。@RomanPerekhrest我怎样才能匹配它呢”您好,这个解决方案对原始字符串也很好。我玩了一点,我看到如果我们有字符串
startend startend
,这个正则表达式只匹配
obj4
,而不匹配
obj3
,它的深度与
obj4
相同。您好,它也适用于类似字符串的
start>end>end>end obj2 startend startend
。我尝试使用与原始字符串类似且更复杂的其他类型的字符串来测试此正则表达式。谢谢。@MatteoVR您的意思是使用re.findall(),对吗?您好,是的,我在脚本中使用re.findall()。如何匹配?”
s= "start< obj1 obj2 start< obj3 >end"
m=re.search(r"start<\s*([^<]*?)\s*>end",s)
>>> m[1]
>>> 'obj3'