![](/img/trans.png)
[英]How to find matching strings upto a specific string with regex in Python
[英]regex: find strings that start with [[ and specific string
我有這些字符串:
[[:File:Example.jpg]]
[[:File:Example.jpg|this example]]
[[Media:Example.jpg]]
[[Georgia (U.S. state)|Georgia]]
[[Arkansas]]
[[Canada]]
[[Virginia]]
[[Image:Houstonia longifolia - Long Leaf Bluet 2.jpg|thumb|left]]
我想提取re
與啟動串[[Image
或[[Media:
或[[:file:
要查找以[[:File:
開頭的字符串,您可以使用:
re.search(r"\[\[:File.*?]]", your_strings)
與[[Media:
和[[Image
:
re.search(r"\[\[Media:.*?]]", your_strings)
re.search(r"\[\[Image.*?]]", your_strings)
請參閱此示例。
試試這個正則表達式
僅在字符串開頭有[[Image
, [[Media:
或[[:File:
時才輸出(還添加了re.IGNORECASE
標志以在任何情況下進行匹配)
\\[\\[(?:Image|Media|:File):.+]]
代碼:
import re
a = '''[[:File:Example.jpg]]
[[:File:Example.jpg|this example]]
[[Media:Example.jpg]]
[[Georgia (U.S. state)|Georgia]]
[[Arkansas]]
[[Canada]]
[[Virginia]]
[[Image:Houstonia longifolia - Long Leaf Bluet 2.jpg|thumb|left]]'''
print(re.findall(r'\[\[(?:Image|Media|:File):.+]]', a, flags=re.IGNORECASE))
輸出:
[
'[[:File:Example.jpg]]',
'[[:File:Example.jpg|this example]]',
'[[Media:Example.jpg]]',
'[[Image:Houstonia longifolia - Long Leaf Bluet 2.jpg|thumb|left]]'
]
告訴我它是否不起作用...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.