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