apelliciari
apelliciari

Reputation: 8501

Regex: how to stop match on certain words that cannot exists

The title is so confusing, I admit it - if you want to change it you are welcome.

I'm working on PHP and preg_match function.

The problem is this string (just an example)

ON DELETE SET NULL ON UPDATE CASCADE

ON DELETE CASCADE ON UPDATE CASCADE (another example..)

i need to find ON DELETE and ON UPDATE values, but they can't be there both.

So sometimes i have this:

ON DELETE something

and other times:

ON UPDATE something

and other times both.

So, this regex doesn't cover all possibilities:

/ON DELETE (.+) ON UPDATE (.+)/

If i put

/ON DELETE (.+)( ON UPDATE (.*))?/ -- to cover the case in which there isn't ON UPDATE

if ON UPDATE is present, first group results in "SET NULL ON UPDATE CASCADE".

How can i do that?

Upvotes: 1

Views: 310

Answers (3)

morja
morja

Reputation: 8560

Use lookaround if you want to avoid matching too much:

Negative lookahead :

/ON DELETE ((?:(?! ON UPDATE).)+)( ON UPDATE (.*))?/

To capture disregarding the order:

/(?:ON DELETE ((?:(?! ON UPDATE).)+)|ON UPDATE ((?:(?! ON DELETE).)+))/

But what exactly do you want? Remove both if they exist?

Upvotes: 2

Matt
Matt

Reputation: 3848

psuedo code to match occurance of on delete and on update but not both

function valid(str)
{
 matchDelete=regex(str, 'ON DELETE'); //true for match
 matchUpdate=regex(str, 'ON UPDATE'); //true for match

 if(   (matchDelete || matchUpdate ) && !(matchDelete && matchUpdate)  )
 {
   valid match
 }
}

Upvotes: 0

bw_üezi
bw_üezi

Reputation: 4574

use Rubular to check your regexp

Upvotes: 0

Related Questions