NordicFox
NordicFox

Reputation: 145

Replace a digit in a sentence using re.sub() in python

I am trying to use re.sub() to replace the total score in the sentence. For example, in Your score for quiz01 is 6/8., I want to replace the total score to 9, the expected output is Your score for quiz01 is 6/9..

I tried the code below but it keeps return (?!([a-zA-Z]+))(?:.+?)([0-9]\/9). **. How should I modify the regex to replace the digit correctly?

import re
s = '** Your score for quiz01 is 6/8. **'

print(re.sub(r'(?!([a-zA-Z]+))(?:.+?)([0-9]\/[0-9])', r'(?!([a-zA-Z]+))(?:.+?)([0-9]\/9)', s))

# result print as (?!([a-zA-Z]+))(?:.+?)([0-9]\/9). **

Upvotes: 2

Views: 557

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

You may use

re.sub(r'(\d/)\d(?!\d)', r'\g<1>9', s)

See the regex demo. The regex matches

  • (\d/) - Group 1 (referred to with the \g<1> unambiguous backreference from the replacement pattern; the \g<N> syntax is required since, after the backreference, there is a digit): a digit and a / char
  • \d - a digit
  • (?!\d) - not followed with any other digit.

See the Python demo:

import re
s = "Your score for quiz01 is 6/8."
print( re.sub(r"(\d/)\d(?!\d)", r"\g<1>9", s) )
# => Your score for quiz01 is 6/9.

Upvotes: 2

Related Questions