代码之家  ›  专栏  ›  技术社区  ›  q3e

在react路由器路径属性中使用regex

  •  2
  • q3e  · 技术社区  · 7 年前

    我正在使用regex而不是string将页面路由到404 react-router path prop

    我有一个不同路线的列表,格式如下:

    路线1

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

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

    反应路由器路由路径regex

    对于路线1

    Route(exact path=myRegex1 render=404)
    

    myRegex1

    使用上述regex,应通过以下操作:

    • /用户/123/depositaaaaa

    应该失败

    • /用户/123/取款
    • /用户/123/押金/
    • /用户/123/押金/
    • /用户

    对于路线2

    Route(exact path=myRegex2 render=404)
    

    myRegex2 . 这些应该通过:

    • /组/未找到/找到

    应该失败

    • /集团/
    • /团体/存款
    • /分组/撤回

    如何让regex知道我需要这些词 deposit withdraw user 作为一个词而不仅仅是一组字符,考虑到我是排除它们而不是包括它们。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Wiktor Stribiżew    7 年前

    您需要告诉regex引擎,您只想避免将url与 withdraw deposit 最后:

    ^\/user\/?[0-9]+\/(?!(?:deposit|withdraw)\/?$).*$
                                             ^^^^
    

    regex demo

    (?!(?:deposit|withdraw)\/?$) 一旦匹配(立即位于当前位置的右侧),负lookahead将使匹配失败:

    • (?:deposit|withdraw) -两个值中的任何一个, 撤退
    • \/? -一或零(可选) / 字符
    • $
    推荐文章