簡體   English   中英

正則表達式:查找以 [[ 和特定字符串開頭的字符串

[英]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]]'
]

Regex101 演示

告訴我它是否不起作用...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM