[英]Using regex in react router Route path prop
我正在通過使用正則表達式而不是react-router path prop中的字符串將我的頁面路由到 404
我所擁有的是以下格式的不同路線的列表:
示例定義
const withdrawRuote = 'user/:userId/withdraw'
const depositRoute = 'user/:userId/deposit'
const groupNewRoute = 'group/new'
const groupWithdrawRoute = 'group/withdraw'
const groupDepositRoute = 'group/deposit'
對於 Route1
Route(exact path=myRegex1 render=404)
這是myRegex1
使用上述正則表達式,以下內容應該通過:
應該失敗
對於 Route2
Route(exact path=myRegex2 render=404)
這是myRegex2 。 這些應該通過:
應該失敗
我知道我可以使用 switch 語句處理 404,但我需要知道為什么這不起作用。
我如何讓正則表達式知道我需要單詞deposit
和withdraw
或user
作為一個單詞,而不僅僅是一組字符,考慮到我將它們排除在外而不是包含。
您需要告訴正則表達式引擎,您只想避免在末尾使用withdraw
和deposit
來匹配 URL:
^\/user\/?[0-9]+\/(?!(?:deposit|withdraw)\/?$).*$
^^^^
查看正則表達式演示
(?!(?:deposit|withdraw)\\/?$)
負向先行一旦匹配(立即在當前位置的右側(?!(?:deposit|withdraw)\\/?$)
將導致匹配失敗:
(?:deposit|withdraw)
- 兩個值之一, deposit
或withdraw
\\/?
- 一或零(可選) /
字符$
- 字符串的結尾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.