在特定条件下匹配第二组(使用单个正则表达式)(Matching a second group under specific conditions (using one single regex))
考虑这个正则表达式:
<a href(="(?:/user)?/([^"]+))">我想要的是,如果在第二个捕获组中,如果有全部/唯一数字,那么此正则表达式不应该匹配。 一个例子:
<a href="/user/15594243"> #this should not match任何解决方案? 我只想要一个正则表达式解决方案,我知道我可以通过使用更多的python代码实现这一点。
Consider this regex:
<a href(="(?:/user)?/([^"]+))">What i want is that if in the second capturing group if there is all/only digits then this regex should not match. An example:
<a href="/user/15594243"> #this should not matchAny solution for that? I want a regex solution only, i know i can achieve this by using further python code.
最满意答案
所有数字和引用的否定先行断言都是我认为需要的“
user_re = re.compile('<a href(="/(?!(?:user/)?[0-9]+").+)"') In [74]: [(url,user_re.match(url) and user_re.match(url).group(1)) for url in ['<a href="/user/15594243">', '<a href="/user/15594243_">', '<a href="/user/user15594243">', '<a href="/user/1">', '<a href="/user/15594243/add">', '<a href="/item/15594243">', '<a href="/a"', '<a href="/15594243">']] Out[74]: [('<a href="/user/15594243">', None), ('<a href="/user/15594243_">', '="/user/15594243_'), ('<a href="/user/user15594243">', '="/user/user15594243'), ('<a href="/user/1">', None), ('<a href="/user/15594243/add">', '="/user/15594243/add'), ('<a href="/item/15594243">', '="/item/15594243'), ('<a href="/a"', '="/a'), ('<a href="/15594243">', None)]编辑 :我知道我上次编辑两次正则表达式,但这只是为了显示目的。
Negative lookahead assertion for all numbers and a quote is all that I think is needed"
user_re = re.compile('<a href(="/(?!(?:user/)?[0-9]+").+)"') In [74]: [(url,user_re.match(url) and user_re.match(url).group(1)) for url in ['<a href="/user/15594243">', '<a href="/user/15594243_">', '<a href="/user/user15594243">', '<a href="/user/1">', '<a href="/user/15594243/add">', '<a href="/item/15594243">', '<a href="/a"', '<a href="/15594243">']] Out[74]: [('<a href="/user/15594243">', None), ('<a href="/user/15594243_">', '="/user/15594243_'), ('<a href="/user/user15594243">', '="/user/user15594243'), ('<a href="/user/1">', None), ('<a href="/user/15594243/add">', '="/user/15594243/add'), ('<a href="/item/15594243">', '="/item/15594243'), ('<a href="/a"', '="/a'), ('<a href="/15594243">', None)]EDIT: I know my last edit does the regex twice but that is just for display purposes.
更多推荐
发布评论