Home > other >  re.sub(): I would like replace list of words following number with some string
re.sub(): I would like replace list of words following number with some string

Time:09-04

want to replace text from list of words followed by number.

list1 = ['apple', 'orange']
text = 'the books are good apple34'
word = re.sub(r'|'.join(list1) [0-9],ball,text)

CodePudding user response:

The re.sub should look like

re.sub(rf"(?:{'|'.join(map(re.escape, list1))})\d ", 'ball', text)

Or, if you need whole word matching:

re.sub(rf"\b(?:{'|'.join(map(re.escape, list1))})\d \b", 'ball', text)

Or even

re.sub(rf"(?!\B\w)(?:{'|'.join(map(re.escape, list1))})\d \b", 'ball', text)

if the list1 items can start with non-word characters. See the online Python demo.

Details

  • (?!\B\w) - a left-hand adaptive dynamic word boundary
  • (?:{'|'.join(map(re.escape, list1))}) - a non-capturing group matching one of the strings defined in list1 (each of which is escaped with re.escape)
  • \d - one or more digits
  • \b - a word boundary.
  • Related