我正在努力使用正则表达式而不是 react-router path prop 中的字符串将我的页面路由到 404
我拥有的是以下格式的不同路线的列表:
示例定义
路线1
const withdrawRuote = 'user/:userId/withdraw'
const depositRoute = 'user/:userId/deposit'
路线2
const groupNewRoute = 'group/new'
const groupWithdrawRoute = 'group/withdraw'
const groupDepositRoute = 'group/deposit'
react-router 路由路径正则表达式
对于路线1
Route(exact path=myRegex1 render=404)
这里是myRegex1
使用上述正则表达式,以下内容应该通过:
- /user/123/withdrawaaaaa
- /user/123/depositaaaaaa
应该失败
- /user/123/withdraw
- /user/123/存款/
- /user/123/withdraw
- /user/123/存款/
- /用户
- /用户/
对于路线2
Route(exact path=myRegex2 render=404)
这里是myRegex2 。 这些应该通过:
- /group/not/found
- /组/不
应该失败
- /组/
- /组
- /组/存款
- /组/退出
我知道我可以使用 switch 语句处理 404,但我需要知道为什么这不起作用。
如何让正则表达式知道我需要将单词 deposit
和 withdraw
或 user
作为一个单词而不仅仅是一组字符考虑到我排除它们而不是包含它们。
最佳答案
您需要告诉正则表达式引擎您只想避免匹配末尾带有 withdraw
和 deposit
的 URL:
^\/user\/?[0-9]+\/(?!(?:deposit|withdraw)\/?$).*$
^^^^
请参阅regex demo
(?!(?:deposit|withdraw)\/?$)
负向预测一旦匹配就会失败(紧邻当前位置的右侧):
(?:deposit|withdraw)
- 两个值之一,deposit
或withdraw
\/?
- 1 个或 0 个(可选)/
字符$
- 字符串结尾。
关于javascript - 在 react 路由器中使用正则表达式 Route path prop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51967545/