2

I have a regular expression which processes a URL with all alphanumeric chars including - and _. I would like to add an exception, so it will not process the URLs /basic and /advance

/?([a-zA-Z0-9_-]+)?/?([a-zA-Z0-9_-]+)?/?([0-9_-]+)?

It should process everything above, except the words "basic" and "advance".

How can I add an exception in above regular expression.

I tried to do something below but it did not work.

/?([a-zA-Z0-9_-]+^(?!basic) ^(?!advance))?/?([a-zA-Z0-9_-]+)?/?([0-9_-]+)?

Any ideas?

I used following link for guide line.

String negation using regular expressions
Regular Expressions and negating a whole character group
What is a non-capturing group? What does a question mark followed by a colon (?:) mean?

Community
  • 1
  • 1
Developer
  • 25,073
  • 20
  • 81
  • 128
  • 1
    Is there a reason that needs to be included into the regular expression, rather than using your programming language to exclude URLs using simple text comparison before using the regex? – 0xCAFEBABE Jun 20 '12 at 08:35
  • actually I am using this in zend system. first regex is already there routing urls to single controller and module with product ids and sub ids. I need to add a exception so that I can route basic and advance to a different controller and module. I can do this using programatically. but i would like to do this in a right way. – Developer Jun 20 '12 at 08:42

2 Answers2

0

Something like /\/(?!basic\/)(?!advance\/)([a-zA-Z0-9_-]+)?\/([a-zA-Z0-9_-]+)?\/([0-9_-]+)?/ should do the job if the 'basic' or 'advance' can only stand in the beginning of the sequence. I don't think you need the ^ symbols before the negative lookahead component, nor a space in between.

Here's a script to test it:

<?PHP
    $ptn = "/\/(?!basic\/)(?!advance\/)([a-zA-Z0-9_-]+)?\/([a-zA-Z0-9_-]+)?\/([0-9_-]+)?/";
    $str = '/basic/asdasd/123'; 
    preg_match($ptn, $str, $match1);
    print_r($match1);
    $str = '/bazic/asdasd/123';
    preg_match($ptn, $str, $match2);
    print_r($match2);
?>
Qnan
  • 3,714
  • 18
  • 15
  • Well, I'm not extremely familiar with the workings of Zend framework, but the following script does distinguish between things that start with 'basic' or 'advance' and all the other matching strings, which is, I understand, the point of the question. `` – Qnan Jun 20 '12 at 10:29
  • (added the script to the answer itself to make it more readable) – Qnan Jun 20 '12 at 10:39
0

Check this, but anyway other not alphanumeric characters also matched!

/?([a-zA-Z0-9_-]+)?/?(?!.*(?:begin|advance))([a-zA-Z0-9_-]+)?/?([0-9_-]+)?

Debuggex Demo

Adam
  • 126
  • 9