Home > front end >  Regex to keep specific word from string
Regex to keep specific word from string

Time:06-13

I'm looking for a regex to keep only specific words or regex into my string. This regex match with what I want to keep (DATE|ADDRESSE|phone|\d{1,}(\.\d{1,2}|\%))

For example,

Input

s='this is an example from DATE and this is my phone and 5.50$'

Desired output

'DATE phone 5.50'

I tried with '[^(DATE|ADDRESSE|phone|\d{1,}(\.\d{1,2}|\%))]' but it keeps characters and not the word.

Do you know how to do it ?

CodePudding user response:

import re

s = "this is an example from DATE and this is my phone and 5.50$"

re_first = re.search(r"\bD\w ", s)
re_second = re.search(r"\bp\w ", s)
re_third = re.search(r"\d.*", s)

print(re_first.group(), re_second.group(), re_third.group())
  • Related