【发布时间】:2014-06-17 03:48:29
【问题描述】:
我正在尝试在 python 中编写一个正则表达式来查找 Markdown 文本字符串中的 url。 找到网址后,我想检查它是否由降价链接包装:文本 我对后者有问题。我正在使用正则表达式 - link_exp - 进行搜索,但结果不是我所期望的,我无法理解它。
这可能是我没有看到的简单的东西。
这里是 link_exp 正则表达式的代码和解释
import re
text = '''
[Vocoder](http://en.wikipedia.org/wiki/Vocoder )
[Turing]( http://en.wikipedia.org/wiki/Alan_Turing)
[Autotune](http://en.wikipedia.org/wiki/Autotune)
http://en.wikipedia.org/wiki/The_Voder
'''
urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', text) #find all urls
for url in urls:
url = re.escape(url)
link_exp = re.compile('\[.*\]\(\s*{0}\s*\)'.format(url) ) # expression with url wrapped in link syntax.
search = re.search(link_exp, text)
if search != None:
print url
# expression should translate to:
# \[ - literal [
# .* - any character or no character
# \] - literal ]
# \( - literal (
# \s* - whitespaces or no whitespace
# {0} - the url
# \s* - whitespaces or no whitespace
# \) - literal )
# NOTE: I am including whitespaces to encompass cases like [foo]( http://www.foo.sexy )
我得到的输出只有:
http\:\/\/en\.wikipedia\.org\/wiki\/Vocoder
这意味着表达式仅在右括号之前找到带有空格的链接。 这不仅是我想要的,而且应该只考虑一个没有空格的案例链接。
你觉得你能帮我解决这个问题吗?
干杯
【问题讨论】:
-
旁注,您可以通过指定
re.VERBOSE在正则表达式中添加您的 cmets。