Reputation: 2286
I am working on routing my pages to 404 by using regex instead of a string in react-router path prop
What I have is a list of different routes in the following format:
example defintions
const withdrawRuote = 'user/:userId/withdraw'
const depositRoute = 'user/:userId/deposit'
const groupNewRoute = 'group/new'
const groupWithdrawRoute = 'group/withdraw'
const groupDepositRoute = 'group/deposit'
For Route1
Route(exact path=myRegex1 render=404)
here is myRegex1
With the above regex, the following should PASS:
should FAIL
For Route2
Route(exact path=myRegex2 render=404)
Here is myRegex2. These should PASS:
should FAIL
I know I can handle 404s using the switch statement but I need to know why this does not work.
How do I make regex know that i need the words deposit
& withdraw
or user
as a word and not just a set of characters considering I am excluding them rather than include.
Upvotes: 2
Views: 7368
Reputation: 626803
You need to tell the regex engine that you want to only avoid matching URLs with withdraw
and deposit
at the end:
^\/user\/?[0-9]+\/(?!(?:deposit|withdraw)\/?$).*$
^^^^
See the regex demo
The (?!(?:deposit|withdraw)\/?$)
negative lookahead will fails the match once it matches (immediately to the right of the current location):
(?:deposit|withdraw)
- either of the two values, deposit
or withdraw
\/?
- one or zero (optional) /
chars$
- end of string.Upvotes: 2