-1

Reading through stack overflow examples i couldn't find a working solution for the below test case.

I need to match a pattern being tested against a list of strings..

the pattern should match if word1 exist, but word2 doesn't exist before it. Any character can exist in between.

Examples: pattern - match if word tty_osc exist and mov_osc doesn't exist anywhere before it.

  1. abd.defg.mov_osc.ccr.tty_osc.val - doesn't match... tty_osc exist but mov_osc also exist before tty_osc
  2. abd.defg.ccr.tty_osc.val - match - tty_osc exist, no mov_osc before

I've tried the following negative lookbehind regex - (?<!mov_osc).*tty_osc

NirMH
  • 4,769
  • 3
  • 44
  • 69
  • It would be awesome if you could provide a [mcve] of what you have you have tried so far. Even better if the examples you have provided in your question were included in the sample code. – mjwills Jun 30 '19 at 13:31
  • 1
    You need to perform two tests. One to check if mov_osc is not before tty_osc and then 2nd test to check if tty_osc does exist. – jdweng Jun 30 '19 at 13:32
  • Move the `.*` inside of the negative look behind. It doesn't work because it's matching everything before tty_osc and then looking for mov_osc before that. – juharr Jun 30 '19 at 13:35

2 Answers2

0

You could use a negative lookahead to assert what is on the right is not your forbidden word followed by the accepted word.

^(?!.*?\bmov_osc\b.*?\btty_osc\b).*?\btty_osc\b.*$

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • FYI your demo is using PHP which might not behave the same as C#. – juharr Jun 30 '19 at 13:42
  • @juharr It will work the same in C#. Just this way, the whole string will get matched, not just the `tty_osc` string. – Wiktor Stribiżew Jun 30 '19 at 13:43
  • @WiktorStribiżew I mean in general you should use a regular expression tester that matches the engine being using. – juharr Jun 30 '19 at 13:44
  • @juharr That is a fair point, it works in C# as well. If the string should be matched until the accepted word then this pattern could be `^(?!.*?\bmov_osc\b.*?\btty_osc\b).*?\btty_osc\b` – The fourth bird Jun 30 '19 at 13:55
0

You need to move the .* inside of the negative look behind (?<!mov_osc.*)tty_osc. Otherwise it will match everything before tty_osc and the negative look behind would just check against the beginning of the string.

RegexStorm.Net Demo

juharr
  • 31,741
  • 4
  • 58
  • 93