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: always true

a = re.compile('(?P.*)')

# return _'yes'_ or 'no' based on

a.sub('(?(\g)yes|no)', 'word')

'(?(word)yes|no)'

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

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

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

解决方案

If you want to perform a conditional substitution, use a function

as the replace parameter.

This function accepts a match parameter (what has been caught)

and its result is the text to be substituted in place of the match.

To refer in the replace function to the capturing group named test,

use group('test').

Example program:

import re

def replTxt(match):

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

a = re.compile('(?P.+)')

result = a.sub(replTxt, 'word')

print(result)

But I have such a remark:

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.

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

has been matched:

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[a-z]+)?\d.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值