gpt4 book ai didi

python 正则表达式无法识别 Markdown 链接

转载 作者:行者123 更新时间:2023-11-28 21:20:07 25 4
gpt4 key购买 nike

我正在尝试在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com