【问题标题】:python regex fails to identify markdown linkspython 正则表达式无法识别降价链接
【发布时间】: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。

标签: python regex markdown


【解决方案1】:

这里的问题是您首先要提取 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 正则表达式。

【讨论】:

  • 感谢@Jon Betts 成功了!简化的 url 正则表达式比我以前使用的非常复杂、难以阅读的表达式更有意义。
  • @MrCastro 你的代码很棒。你能像我问的here那样修改它以更改markdown文件中的链接吗?提前致谢,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-29
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-04
相关资源
最近更新 更多