[英]Python: Regex finds only part of sought string
content
變量包含多行字符串:
content = """
/blog/1:text:Lorem ipsum dolor sit amet, consectetur ### don't need this
<break>
text:Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
<break>
text:Excepteur sint occaecat cupidatat non proident.
/blog/16:text:Other Lorem ipsum dolor ### SEEKING THIS!!!
<break>
text:Other, really other
<break>
text:Blah blah.
"""
我正在嘗試使用模式/ blog / 16查找所需的出現:
re.findall('^(?ism)%s?:(.*?)(\n\n)' % '/blog/16', content)
並期望得到這個
[(u'/blog/16:text:Other Lorem ipsum dolor ### SEEKING THIS!!!
<break>
text:Other, really other
<break>
text:Blah blah.', u'\n\n')]
但是得到錯誤的結果( / blog / 1 )
[(u'/blog/1:text:Lorem ipsum dolor sit amet, consectetur ### don't need this
<break>
text:Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
<break>
text:Excepteur sint occaecat cupidatat non proident.', u'\n\n')]
我怎么了
字符串替換完成后,您的字符串如下所示
^(?ism)/blog/16?:(.*?)(\n\n)
在這里, ?
表示匹配上一個模式0或1次。 因此,當輸入為/blog/1
,它匹配0
次並允許匹配。
您正在尋找的實際RegEx是,
import re
print re.findall('(?ims)(/blog/16:.*)(?:/blog|$)', content)
產量
['/blog/16:text:Other Lorem ipsum dolor ### SEEKING THIS!!!\n<break>\ntext:Other, really other\n<break>\ntext:Blah blah.\n']
插入博客文本后,這是正則表達式的這一部分:
/blog/16?:
意思是“匹配: /blog/1
字面;然后6
字面(零或一遍);然后:
字面”。 相反,請嘗試:
(?ism)^/blog/16:(.*?)$
這將查找/blog/16:
所有內容/blog/16:
從字面上看是在行的開頭,然后進行非貪婪搜索以查找直到行末的所有字符(即,捕獲行中的其余文本)。
您可能會發現regex101對於開發和測試正則表達式很有用。
我認為您忘了將非捕獲組放在括號中。 ?:
。 現在,你?
說“前一個元素的0或1”,這意味着6是不必要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.