我正在尝试用 python 编写一个正则表达式来查找 Markdown 文本字符串中的 url。
找到 url 后,我想检查它是否被 markdown 链接包裹:text
我对后者有疑问。我正在使用正则表达式 - 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
这意味着表达式仅查找右括号之前带有空格的链接。
这不仅是我想要的,而且只应考虑一种没有空格的链接。
你认为你能在这件事上帮我吗?
cheers
这里的问题是你的正则表达式首先提取 URL,其中包括)
在 URL 内。这意味着您要查找右括号两次。除了第一个之外,所有的事情都会发生这种情况(空间可以节省你的时间)。
我不太确定你的 URL 正则表达式的每个部分试图做什么,但那部分说:[$-_@.&+]
,包括从$
(ASCII 36) 至_
(ASCII 137),其中包含大量您可能不想要的字符,包括)
.
与其先查找 URL,然后检查它们是否在链接中,为什么不同时执行这两项操作呢?这样你的 URL 正则表达式就可以变得更懒,因为额外的约束使它不太可能是其他东西:
# Anything that isn't a square closing bracket
name_regex = "[^]]+"
# http:// or https:// followed by anything but a closing paren
url_regex = "http[s]?://[^)]+"
markup_regex = '\[({0})]\(\s*({1})\s*\)'.format(name_regex, url_regex)
for match in re.findall(markup_regex, text):
print match
Result:
('Vocoder', 'http://en.wikipedia.org/wiki/Vocoder ')
('Turing', 'http://en.wikipedia.org/wiki/Alan_Turing')
('Autotune', 'http://en.wikipedia.org/wiki/Autotune')
如果您需要更严格,您可以改进 URL 正则表达式。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)