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
You can escape it by preceding it with a \ (making it \/ ), or you could use new RegExp('/') to avoid escaping the 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.
$ means "Match the end of the string" (the position after the last character in the string).
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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With