Home > Net >  How to replace a pattern in string using python
How to replace a pattern in string using python

Time:05-02

I would like to use regex to replace a pattern (starting with "T_" and ending with "_D") with "0" in string. For example, "xT_a_DxT_b_c_Dx" will be changed to "x0x0x". The code below doesn't work because the txt starts and ends with "x". How to make it work? Thanks!

import re
txt="xT_a_DxT_b_cDx"
print(re.sub("^T_.*_D$", "0", txt))

CodePudding user response:

Try this:

import re
test_str = "xT_a_DxT_b_c_Dx"
result = re.sub(r"T_[^D] _D", "0", test_str)
if result:
    print (result)
# x0x0x

Test here: https://regex101.com/r/mT5evw/1

T_[^D] _D

T_    match literal char 'T_'
[^D]  match anything that is not 'D'( ie match everything till D is found)
_D     match literal char '_D'

CodePudding user response:

You may try:

txt = 'xT_a_DxT_b_cDx'
output = re.sub(r'(?<=x)T(?:_\w )*?_?D(?=x)', '0x0', txt)
print(output)  # x0x0x
  • Related