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

NordicFox

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). **
Wiktor Stribiżew

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Replace "&&" with "and" using re.sub in python.

Using python re.sub, but it replace the start and end unexpected

How to replace a word suffix using re.sub() in Python?

Using re.sub() in python to replace html code

Converting strings in a dataframe to uppercase using the python re package replace function (re.sub)

Replace strings in a list (using re.sub)

How to replace character $ by using re.sub?

Replace multiple characters using re.sub

Replace words in a sentence with synonyms using Python

Python re.sub replace with matched content

Python re.sub replace html attributes

Python re.sub does not replace newline

Python re.sub does not replace

replace mapped drive k:/ and K:\ with the unc path in all files in drive using python re sub

Using re.sub() in python how to replace certain phrase but only if there is more than one letter ahead of it

Python replace a string using re.sub only if prefix and suffix matches

String replacements using re.sub in python

Using re.sub with capture groups to replace only portion of a match

Using re.sub() to replace some part of a string

How to search and replace exact character and number using re.sub?

Replace second and last second characters, using re.sub

How to find a sentence containing a phrase in text using python re?

python re.sub replace number in match string

Python re.sub(): trying to replace escaped characters only

python re.sub, only replace part of match

re.sub to replace multiple lists with corresponding matches (Python)

Python re.sub with a flag does not replace all occurrences

Use Python's string.replace vs re.sub

How to replace only part of the match with python re.sub