条件构造在 Python 正则表达式中不起作用 [英] Conditional construct not working in Python regex

查看:73
本文介绍了条件构造在 Python 正则表达式中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手,我想在 re.sub 中使用我的正则表达式.我在 regex101 上试了一下,效果很好.不知何故,当我尝试在我的 python(3.6 版)上使用它时,它无法正常工作.我收到以下警告

I an a newbie in python and I want to use my regex in re.sub. I tried it on regex101 and it works. Somehow when I tried to use it on my python (version 3.6) it doesn't work properly. I get the following warning

组名 '?=[^\t]*' 在第 5 位的错误字符

bad character in group name '?=[^\t]*' at position 5

这是我的代码:

re = r"(?(?=[^\t]*)([\t]+))";
str = 'a            bold, italic,           teletype';
subst = ',';

result = re.sub($re, $subst, $str);

推荐答案

问题是您不能在 Python re 的条件结构中使用环视.仅捕获组 ID 以测试前一组是否匹配.

The problem is that you cannot use lookarounds in conditional constructs in a Python re. Only capturing group IDs to test if the previous group matched.

(?(id/name)yes-pattern|no-pattern)
如果具有给定 id 或名称的组存在,将尝试与 yes-pattern 匹配,如果不存在,则与 no-pattern 匹配.no-pattern 是可选的,可以省略.

(?(id/name)yes-pattern|no-pattern)
Will try to match with yes-pattern if the group with given id or name exists, and with no-pattern if it doesn’t. no-pattern is optional and can be omitted.

(?(?=[^\t]*)([\t]+)) 正则表达式检查当前位置是否有除制表符以外的 0+ 个字符,如果有, 匹配并捕获 1 个或多个选项卡.这没有任何意义.如果你想匹配 1 个或多个标签的第一次出现,你可以使用 re.sub 和一个 "\t+" 模式和 count=1 参数.

The (?(?=[^\t]*)([\t]+)) regex checks if there are 0+ chars other than tabs at the current location, and if yes, matches and captures 1 or more tabs. This makes no sense. If you want to match the first occurrence of 1 or more tabs, you may use re.sub with a mere "\t+" pattern and count=1 argument.

import re
reg = "\t+";
s = 'a          bold, italic,           teletype';
result = re.sub(reg, ',', s, count=1);
print(result);

查看 Python 演示

这篇关于条件构造在 Python 正则表达式中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆