我正在尝试在 python 中编写一个正则表达式来在 Markdown 文本字符串中查找 url。
找到 url 后,我想检查它是否被 Markdown 链接包裹:文本
我对后者有问题。我正在使用正则表达式 - 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

这意味着表达式仅在右括号之前找到带有空格的链接。
这不仅是我想要的,而且应该只考虑一种没有空格的案例链接。

你认为你能帮我解决这个问题吗?
干杯

最佳答案

这里的问题是您首先提取 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

结果:
('Vocoder', 'http://en.wikipedia.org/wiki/Vocoder ')
('Turing', 'http://en.wikipedia.org/wiki/Alan_Turing')
('Autotune', 'http://en.wikipedia.org/wiki/Autotune')

如果您需要更严格,您可能可以改进 URL 正则表达式。

关于python正则表达式无法识别 Markdown 链接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23394608/

10-14 13:13
查看更多