Regex: replace Latin numbers after a word

Viewed 75

I have a text like this: it's level I, not level II or level III.

I want the I after level to turn into 1 and only on level I.

I tried this code : text = re.sub(r'(level I)+[\s,.]',r'level 1 ',text)

But i get my output like this: it's level 1 not level II or level III.

and the comma is skipped which i don't want it to be ignored. also in some cases

i have the word Level not level.

1 Answers

You can use

import re
text = "it's level I, not level II or level III. It's Level I, not Level II or Level III."
print(re.sub(r'\b([lL]evel\s+)I\b', r'\g<1>1', text))
# => it's level 1, not level II or level III. It's Level 1, not Level II or Level III.
print(re.sub(r'(?<=\b[lL]evel )I\b', '1', text))
# => it's level 1, not level II or level III. It's Level 1, not Level II or Level III.

See the Python demo.

Notes:

  • \b([lL]evel\s+)I\b - matches a whole word level followed with one or more whitespaces, and then matches a I as a whole word (due to the word boundary) and replaces with the backreference to the group value (\g<1> is an unambigupus backreference syntax used here because the next char is a digit)
  • (?<=\b[lL]evel )I\b - matches a location that is immediately preceded with a whole word level and a space, and then matches a I as a whole word.

NOTE 2: You may also use r'\b((?i:level)\s+)I\b' and r'(?<=\b(?i:level) )I\b' to match level in a completely case insensitive way.

Related