I want to substitute 1st part of the regex matched string. I am using re (regex) package in python for this:
import re
string = 'H12-H121'
sub_string = 'H12'
re.sub(sub_string,"G12",string)
>> G12-G121
Expected Output:
>> G12-H121
I want to substitute 1st part of the regex matched string. I am using re (regex) package in python for this:
import re
string = 'H12-H121'
sub_string = 'H12'
re.sub(sub_string,"G12",string)
>> G12-G121
Expected Output:
>> G12-H121
You should tell engine that you want to do matching and substitution to be done at beginning using ^ anchor:
re.sub('^H12', 'G12', string)
or if you are not sure about string after -:
re.sub('^[^-]+', 'G12', string)
If you only need to replace first occurrence of H12 use parameter count:
re.sub('H12', 'G12', string, count = 1)
^[^-]+ breakdown:
^ Match start of input string[^-]+ Match one or more character(s) except -