Regex to extract a sentence containg a word

Viewed 66

I have a string like this

Good Morning 
Hello There - PROTECT FROM FREEZE
protect from freeze 
FORKLIFT UNLOAD -Please ship it with care
Thank you

I need a regex to match PROTECT FROM FREEZE from both lines and FORKLIFT UNLOAD on the other line I have tried .*FREEZE.* and .*FORKLIFT.* (IGNORED CASE using re.IGNORECASE), But this regex selects the whole line.

This regex gives the output as follows:

Hello There - PROTECT FROM FREEZE
protect from freeze 
FORKLIFT UNLOAD -PLEASE HAVE SKID AT TAIL 

Desired Output:

PROTECT FROM FREEZE
protect from freeze
FORKLIFT UNLOAD
2 Answers

Assuming you just want to match the first series of all caps words on each line, you could try this approach:

inp = """Hello There - PROTECT FROM FREEZE
PROTECT FROM FREEZE 
FORKLIFT UNLOAD -PLEASE HAVE SKID AT TAIL"""

matches = re.findall(r'^.*?\b([A-Z]{2,}(?: [A-Z]{2,})*)', inp, flags=re.MULTILINE)
print(matches)

This prints:

['PROTECT FROM FREEZE', 'PROTECT FROM FREEZE', 'FORKLIFT UNLOAD']

You can use

[^-\n]*F(?:REEZE|ORKLIFT)[^-\n]*

Or, if you need to make sure the freeze and forklift are whole words:

[^-\n]*\bF(?:REEZE|ORKLIFT)\b[^-\n]*

See the regex demo

Details

  • [^-\n]* - zero or more chars other than - and a newline
  • \b - a word boundary
  • F(?:REEZE|ORKLIFT) - same as (?:FREEZE|FORKLIFT), but a bit more efficient
  • \b - a word boundary
  • [^-\n]* - zero or more chars other than - and a newline

See a Python demo:

import re
text = 'Good Morning \nHello There - PROTECT FROM FREEZE\nprotect from freeze \nFORKLIFT UNLOAD -PLEASE HAVE SKID AT TAIL \nThank you'
res = re.findall(r'[^-\n]*\bF(?:REEZE|ORKLIFT)\b[^-\n]*', text, re.IGNORECASE)
print( [x.strip() for x in res] )
## => ['PROTECT FROM FREEZE', 'protect from freeze', 'FORKLIFT UNLOAD']
Related