Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular express : how to exclude multiple character groups?

Tags:

regex

I have a set of urls :

/products

/categories

/customers

Now say a customers is named john, and I want to help john to reach his own account page with a shorter url:

before : /customers/john
after  : /john

(suppose customer names are unique)

I'm trying to figure out a proper regex dispatcher so all customers can have this feature :

/marry
/james
/tony-the-red-beard

here is what I got now(in PHP) :

'/^\/([^(products|categories|admin)].+)$/' => /customers/$1

This doesn't seem to work. Anybody can help me?

like image 545
Shawn Avatar asked Jan 08 '10 05:01

Shawn


People also ask

How do you skip special characters in regex?

for metacharacters such as \d (digit), \D (non-digit), \s (space), \S (non-space), \w (word), \W (non-word). to escape special regex characters, e.g., \. for . , \+ for + , \* for * , \? for ? . You also need to write \\ for \ in regex to avoid ambiguity.

Which regular expression matches any character except XYZ?

Wildcard which matches any character, except newline (\n). Used to match 0 or more of the previous (e.g. xy*z could correspond to "xz", "xyz", "xyyz", etc.) ?!= or ?

What is [] in regular expression?

The [] construct in a regex is essentially shorthand for an | on all of the contents. For example [abc] matches a, b or c. Additionally the - character has special meaning inside of a [] . It provides a range construct. The regex [a-z] will match any letter a through z.


1 Answers

What you need here is a negative lookahead assertion. What you want to say is "I want to match any string of characters, except for these particular strings." An assertion in a regex can match against a string, but it doesn't consume any characters, allowing those character to be matched by the rest of your regex. You can specify a negative assertion by wrapping a pattern in (?! and ).

'/^\/(?!products|categories|admin)(.+)$/'

Note that you might want the following instead, if you don't allow customers names to include slashes:

'/^\/(?!products|categories|admin)([^/]+)$/'
like image 189
Brian Campbell Avatar answered Sep 18 '22 12:09

Brian Campbell