python regex无法识别降价链接

2024-05-08 02:40:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在一个字符串中写下一个python的url。 一旦找到了一个url,我想检查它是否被markdown链接:text包装起来 我对后者有意见。我正在使用regex-link_-exp-来搜索,但是结果不是我所期望的,我无法理解它。在

这可能是我没有看到的简单的事情。在

下面是link_exp regex的代码和解释 在

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   )  

我得到的输出只有:

^{pr2}$

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

你觉得这件事你能帮我吗?
干杯


Tags: ornotextorgrehttpurlsearch
1条回答
网友
1楼 · 发布于 2024-05-08 02:40:16

这里的问题是您的正则表达式首先用于拉出URL,这是在URL中包含)。这意味着您要查找两次右括号。这一切都会发生,除了第一个(空间节省你那里)。在

我不太确定URL regex的每一部分都在尝试做什么,但是这部分内容说明: [$-_@.&+],包含从$(ascii36)到{}(ascii137)的范围,其中包含了大量您可能不是指的字符,包括)。在

与其查找url,然后检查它们是否在链接中,为什么不同时执行这两项操作呢?这样,您的URL regex可以更懒惰,因为额外的约束使它不太可能是其他的:

# 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

结果:

^{pr2}$

如果需要更严格的话,可以改进URL regex。在

相关问题 更多 >