在特定条件下匹配第二组(使用单个正则表达式)(Matching a second group under specific conditions (using one single regex))

编程入门 行业动态 更新时间:2024-10-26 12:35:17
在特定条件下匹配第二组(使用单个正则表达式)(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 match

Any 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.

更多推荐

本文发布于:2023-07-27 15:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1292431.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:条件下   在特定   正则表达式   Matching   group

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!