Eduardo EPF
Eduardo EPF

Reputation: 170

Matching complex regular expression containing regex expression and not containing another string

I am trying to match through regex a string that contains a certain regex pattern and doesn´t contain a substring. However this substring needs to be in a certain location of the string fitting rest of the pattern

I am trying to do this regex

^(-?NODE1-METHOD1-NODE2-).*(?!NODE3)-METHOD2-+

Where I will match all the strings containing NODE1-METHOD1-NODE2- followed by whatever character and that won't have NODE3 and that finally will have METHOD2 followed by -

This regex would match the following string

NODE1-METHOD1-NODE2-METHOD4-NODE5-METHOD5-NODE6-METHOD6-NODE6-METHOD7-NODE7-METHOD2----------------------------

but not this one

NODE1-METHOD1-NODE2-METHOD4-NODE5-METHOD5-NODE3-METHOD2----------------------------

Right now, with the pattern I'm using, I'm not able to match any of the cases. Happy to study other ways to do this. Thanks

Upvotes: 0

Views: 31

Answers (1)

The fourth bird
The fourth bird

Reputation: 163287

Using this part in your pattern .*(?!NODE3)-METHOD2-+ the .* will first match until the the end of the string followed by (?!NODE3) which will be true as it is as the end of the string and there is no NODE3 at the right.

You could check right after closing the first group that the rest of the string does not contain NODE3 using a negative lookahead with a quantifier inside it (?!.*NODE3)

If that succeeds, match any character until you encounter METHOD2 followed by 1 or more hyphens .*METHOD2-+

^(-?NODE1-METHOD1-NODE2-)(?!.*NODE3).*METHOD2-+

Regex demo

Upvotes: 2

Related Questions