0

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
1
  • 1
    do you need to use regex? Why not str.replace? Commented Apr 25, 2018 at 14:45

4 Answers 4

3

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)

Live demo

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 -
Sign up to request clarification or add additional context in comments.

Comments

2

add a 1 for the count of occurrences to replace to the call to re.sub. what i mean is:

import re
string = 'H12-H121'
sub_string = 'H12'
re.sub(sub_string,"G12",string, 1)  #<---- 1 added here

now the output is 'G12-H121' since it only replaces the first match

Comments

2

You can do this with just a str.replace()

full_string = 'H12-H121'
sub_string = 'H12'
output_string = full_string.replace(sub_string,"G12",1)

print(output_string)

outputs:

G12-H121

Comments

1

Just add a ^ to the substring re pattern

import re

s1 = 'H12-H121'
pat = r'^H12'
print(re.sub(pat,"G12",s1))

outputs G12-H121

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.