Creating python regex for exact match of a string with other condition in multi line content

Viewed 47

I have a multiple lines file content like

s1 = """
   Python is a high-level, interpreted,  Good&
   general|purpose| programming| language. 
   Its design philosophy emphasizes code   Better
   readability with the use of significant Best
   indentation| 
   """

I want those lines, where pipe(|) is not there but (Good,Better, Best) should be there. (Good,Better,Best) should be the exact word match.

I have tried multiple ways, but failing

  1. ?=^(?:(?!.*\|).)*$)(.*\bGood\b.*$|.*\bBetter\b.*$|.*\bBest\b.*$ here issue is special chars are not getting avoided like Good& is being as part of result.
  2. (?=^(?:(?!.*\|).)*$).*(^|\s)(Good|Better|Best)($|\s).*$ In this one pipe is not getting skipped if it is last char and results are coming as a groups not lines.

Please help me what I am missing

1 Answers

If you want to match the lines where there is no pipe char | but does contain either one of the words:

^[^|\n]*(?<!\S)(?:Good|Better|Best)(?!\S)[^\n|]*$

Explanation

  • ^ Start of string
  • [^|\n]* Optionally match any char except a pipe or newline
  • (?<!\S)(?:Good|Better|Best)(?!\S) Match any of the words between whitespace boundaries
  • [^|\n]* Optionally match any char except a pipe or newline
  • $ End of string

Regex demo | Python demo

Example code matching the whole lines:

import re

s1 = """
   Python| is a high-level|, interpreted,  Good&
   general|purpose| programming| language. 
   Its design philosophy emphasizes code   Better
   readability with the use of significant Best
   indentation| 
   """
pattern = r'^[^|\n]*(?<!\S)(?:Good|Better|Best)(?!\S)[^\n|]*$'

print(re.findall(pattern, s1, re.M))

Output

['   Its design philosophy emphasizes code   Better', '   readability with the use of significant Best']
Related