在re.sub中有条件的python正规表达式-怎么做? [英] python regex conditional in re.sub - how?

查看:113
本文介绍了在re.sub中有条件的python正规表达式-怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 re.sub()中使用python的正则表达式条件?我尝试了多种尝试,没有碰到运气。这就是我所拥有的。

Is it possible to use python's regex conditionals in re.sub()? I've tried a number of variations without luck. Here's what I have.

import re
# match anything: <test> always true
a = re.compile('(?P<test>.*)')  

# return _'yes'_ or 'no' based on <test>
a.sub('(?(\g<test>)yes|no)', 'word')
'(?(word)yes|no)'

我期望的是是或否,而不是实际测试。

I expected either a 'yes' or 'no,' not the actual test.

我从中得到的是看到了< test> ,但是未执行正则表达式条件。还有另一种方法可以做到这一点吗?

What I get from this is that <test> is seen but the regex conditional isn't being executed. Is there another way of accomplishing this?

我尝试了 re.sub(pat,rep,str)与相同的结果。

I tried with re.sub(pat, rep, str) with same results.

推荐答案

如果要执行条件替换,请使用函数
作为 replace 参数。

If you want to perform a conditional substitution, use a function as the replace parameter.

此函数接受 match 参数(已捕获的内容)
,其结果是要替换匹配项的文本。

This function accepts a match parameter (what has been caught) and its result is the text to be substituted in place of the match.

在替换功能中引用名为 test 的捕获组,
使用 group('test')

To refer in the replace function to the capturing group named test, use group('test').

示例程序:

import re

def replTxt(match):
    return 'yes' if match.group('test') else 'no'

a = re.compile('(?P<test>.+)')  
result = a.sub(replTxt, 'word')
print(result)

但是我有这样的话:

不可能用 no 代替这个程序。
如果正则表达式不匹配,将不会调用 replTxt 函数。

There is no chance that no will ever be substituted by this program. If the regex doesn't match, replTxt function will just not be called.

test 组不匹配但有
匹配的可能性:

To have the possibility that test group matched nothing, but something has been matched:


  • 此捕获组应该为有条件的(在其后为

  • 为了不匹配空文本,正则表达式应包含
    还要匹配的内容,例如(?P< test> [a-z] +)?\d

  • this capturing group should be conditional (? after it),
  • in order not to match an empty text, the regex should contain something more to match, e.g. (?P<test>[a-z]+)?\d.

这篇关于在re.sub中有条件的python正规表达式-怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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