Home > database >  Match everything except a selection of words starting from word1 and ending at word2
Match everything except a selection of words starting from word1 and ending at word2

Time:01-12

I am trying to match 'match me please' within the following String in Python flavor:

bar\nStartOfString\nignoreMe\ntoBeIgnored\nmatch me please\nignoreYou\nEndOfString\nfoo

The result has to exclude ignoreMe, toBeIgnored and ignoreYou as the position of these words is relative.

What I've tried so far:

StartOfString((?!ignoreMe)(?!toBeIgnored)(?!ignoreYou).*)EndOfString

\b(?!ignoreMe|ignoreYou|toBeIgnored)\b\S 

https://regex101.com/r/VaROsW/2

Can anyone please help?

CodePudding user response:

You could use a capture group to capture what you want.

If you want to match \n (backslash and an n char), you can match as least amount of characters between the words in the alternation.

(?:(?:ignore(?:Me|You)|toBeIgnored)\\n) (.*?)\\n(?:ignore(?:Me|You)|toBeIgnored)

Regex demo

If \n is a newline, you can prevent matching the words in the alternation using a negative lookahead:

^(?:ignore(?:Me|You)|toBeIgnored)((?:\n(?!ignore(?:Me|You)|toBeIgnored).*))\n(?:ignore(?:Me|You)|toBeIgnored)

Regex demo

  •  Tags:  
  • Related