简体   繁体   English

在re.sub中有条件的python正则表达式-怎么做?

[英]python regex conditional in re.sub - how?

Is it possible to use python's regex conditionals in re.sub() ? 是否可以在re.sub()使用python的正则表达式条件? 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. 我期望的是“是”或“否”,而不是实际测试。

What I get from this is that <test> is seen but the regex conditional isn't being executed. 我从中得到的是看到了<test> ,但没有执行正则表达式条件。 Is there another way of accomplishing this? 还有另一种方法可以做到这一点吗?

I tried with re.sub(pat, rep, str) with same results. 我尝试使用re.sub(pat, rep, str)获得相同的结果。

If you want to perform a conditional substitution, use a function as the replace parameter. 如果要执行条件替换,请使用函数作为replace参数。

This function accepts a match parameter (what has been caught) and its result is the text to be substituted in place of the match. 此函数接受match参数(已捕获的内容),其结果是要替换匹配项的文本。

To refer in the replace function to the capturing group named test , use group('test') . 要在替换函数中引用名为test的捕获组,请使用group('test')

Example program: 示例程序:

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)

But I have such a remark: 但是我有这样的话:

There is no chance that no will ever be substituted by this program. 有没有这样的机会no永远不会通过该计划来取代。 If the regex doesn't match, replTxt function will just not be called. 如果正则表达式不匹配,则不会调用replTxt函数。

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, eg (?P<test>[az]+)?\\d . 为了不匹配空文本,正则表达式应包含更多要匹配的内容,例如(?P<test>[az]+)?\\d

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM