2

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

route1

const withdrawRuote = 'user/:userId/withdraw'
const depositRoute = 'user/:userId/deposit'

route2

const groupNewRoute = 'group/new'
const groupWithdrawRoute = 'group/withdraw'
const groupDepositRoute = 'group/deposit'

react-router route path regex

For Route1

Route(exact path=myRegex1 render=404)

here is myRegex1

With the above regex, the following should PASS:

  • /user/123/withdrawaaaaa
  • /user/123/depositaaaaaa

should FAIL

  • /user/123/withdraw
  • /user/123/deposit/
  • /user/123/withdraw
  • /user/123/deposit/
  • /user
  • /user/

For Route2

Route(exact path=myRegex2 render=404)

Here is myRegex2. These should PASS:

  • /group/not/found
  • /group/not

should FAIL

  • /group/
  • /group
  • /group/deposit
  • /group/withdraw

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.

1
  • 1
    It's not clear what you have and what you expect. Please write some examples and counterexamples. Commented Aug 22, 2018 at 15:17

1 Answer 1

2

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.
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks. I forgot to mention /user/ or /user should not match.I've updated the question
@fatahn But my regex above does not match /user nor /user/. Please explain what ^\/user\/?[0-9]+ should match. Right now, it matches /user, /user22343 or /user/12234 like strings.
Thanks alot @wiktor-stribiżew, this will do for now,
It does not PASS for /user/not/found
@fatahn That is because of \/?\d+. I asked you for clarifications because you did not explain the rules. If you want to do it once and well, provide exact specs. To match /user/not/found make the \/?\d+ optional, use ^\/user(?=(\/[0-9]+)?)\1\/(?!(?:deposit|withdraw)\/?$).+$
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.