Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - match everything but forward slash

Tags:

regex

in the following string:

/seattle/restaurant

I would like to match Seattle (if it is present) (sometimes the url might be /seattle/restaurant and sometimes it might be /restaurant). What I don't want is to match the following forward slash: seattle/

I have tried the following, but I cannot get it to work:

       /(.*[^/]?)restaurant(\?.*)?$

I need the first forward slash, so the solution is not to remove that, which I can do like this:

     (/?)(.*)/restaurant(\?.*)?$   

Thanks

Thomas

like image 417
ThomasD Avatar asked Feb 14 '12 07:02

ThomasD


People also ask

How do you handle forward slash in regex?

You can escape it by preceding it with a \ (making it \/ ), or you could use new RegExp('/') to avoid escaping the regex.

Is forward slash special in regex?

The forward slash character is used to denote the boundaries of the regular expression: ? The backslash character ( \ ) is the escaping character. It can be used to denote an escaped character, a string, literal, or one of the set of supported special characters.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

What is difference [] and () in regex?

This answer is not useful. Show activity on this post. [] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.


1 Answers

What about something like this?

^/([^/]+)/?(.*)$ 

I tested it with python and seems to work fine:

>>> regex=re.compile(r'^/([^/]+)/?(.*)$') >>> regex.match('/seattle').groups() ('seattle', '') >>> regex.match('/seattle/restaurant').groups() ('seattle', 'restaurant') 
like image 65
jcollado Avatar answered Sep 18 '22 14:09

jcollado