0

How do I search and replace a pattern in text using regular expression in Python 3 ?

import re
text = "|105_Oldtext1.1|309_Oldtext1.1|367_Newtext1.6|413_Newtext1.6|"
result = re.sub("105_*", "105_Newtext1.6", text)
print(result)

what I get as result is:

"|105_Newtext1.6Oldtext1.1|309_Oldtext1.1|367_Newtext1.6|413_Newtext1.6|"

I want to replace 105_(whatever text) by 105_Newtext1.6

1 Answer 1

1

The * isn't a wildcard here ;) You might need this instead:

import re
text = "|105_Oldtext1.1|309_Oldtext1.1|367_Newtext1.6|413_Newtext1.6|"
result = re.sub("105_[^|]*", "105_Newtext1.6", text)
print(result)

* means that the previous character is repeated 0 or more times. So, [^|]* means any character which is not a pipe character being repeated 0 or more times.

Sign up to request clarification or add additional context in comments.

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.