Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  11] [ 3]  / answers: 1 / hits: 6366  / 6 Years ago, wed, august 22, 2018, 12:00:00

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.


More From » regex

 Answers
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.


[#11710] Tuesday, August 21, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jesse

Total Points: 513
Total Questions: 118
Total Answers: 106

Location: Denmark
Member since Tue, Jul 19, 2022
2 Years ago
;