简体   繁体   English

像python中的正则表达式一样替换ACD | BCD

[英]Substitution of ACD|BCD like regular expression in python

A, B, C and D represent different parts of a regular expression. A,B,C和D代表正则表达式的不同部分。

The effect I want to achieve: The input string is ACD or BCD. 我要实现的效果:输入字符串是ACD或BCD。 After substituting C with E, the output should be AED or BED. 用E替换C后,输出应为AED或BED。

The regular expression I used: 我使用的正则表达式:

r=(A)C(D)|(B)C(D)

However, the problem arose when I did the substitution. 但是,当我进行替换时出现了问题。 If I use r.sub(r'\\1s0\\2',inputstring) then there will be an unmatched-group error when the input is BCD. 如果我使用r.sub(r'\\1s0\\2',inputstring)则当输入为BCD时将出现不匹配组错误。 If I use r.sub(r'\\3s0\\4',inputstring) then there will be an unmatched-group error when the input is ACD. 如果我使用r.sub(r'\\3s0\\4',inputstring)则当输入为ACD时会出现组不匹配错误。

So how can I edit the regular expression to avoid this situation? 那么,如何编辑正则表达式以避免这种情况?

Use (A|B)C(D) instead of (A)C(D)|(B)C(D) : 使用(A|B)C(D)代替(A)C(D)|(B)C(D)

import re
r = re.compile(r'(A|B)C(D)')
r.sub(r'\1E\2', 'ACD')    # 'AED'
r.sub(r'\1E\2', 'BCD')    # 'BED'

You can use a substitution function instead of string. 您可以使用替代函数代替字符串。 The return value of the function is used as a replacement string. 该函数的返回值用作替换字符串。

import re

def repl(m):
    # m: the matched object.
    if m.group(1) is not None:
        prefix, suffix = m.group(1), m.group(2)
    else:
        prefix, suffix = m.group(3), m.group(4)
    return '{}E{}'.format(prefix, suffix)

re.sub('(A)C(D)|(B)C(D)', repl, 'ACD') # AED
re.sub('(A)C(D)|(B)C(D)', repl, 'BCD') # BED

Alternatively, if you use regex module instead of Python builtin re module, you can do following: 另外,如果您使用regex模块而不是Python内置的re模块,则可以执行以下操作:

>>> import regex # NOTE: not `re`, but `regex`
>>>
>>> regex.sub('(A)C(D)|(B)C(D)', r'\1\3E\2\4', 'ACD')
'AED'
>>> regex.sub('(A)C(D)|(B)C(D)', r'\1\3E\2\4', 'BCD')
'BED'

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

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