[英]Regex to match specific path with specific query param
我正在努力創建正則表達式以匹配URL路徑與可能在任何地方的查詢參數。
例如,URL可以是:
/page?foo=bar&target=1&test=1 <- should match
/page?target=1&test=2 <- should match
/page/nested?foo=bar&target=1&test=1 <- should NOT match
/page/nested?target=1&test=2 <- should NOT match
/another-page?foo=bar&target=1&test=1 <- should NOT match
/another-page?target=1&test=2 <- should NOT match
我需要在/page
專門針對param target
這個正則表達式只能找到參數\\A?target=[^&]+&*
。
謝謝!
更新:第三方工具需要它來決定運行實驗的頁面。 它只接受儀表板上的設置,並且常規表現,所以我不能使用URL解析器等代碼工具。
一般規則是,如果要解析params,請使用URL解析器,而不是自定義正則表達式。
在這種情況下,您可以使用例如:
# http://a.b/ is just added to make URL parsing work
url = new URL("http://a.b/page?foo=bar&target=1&test=1")
url.searchParams.get("target")
# => 1
url.pathname
# => '/page'
然后在ifs中檢查這些值:
url = new URL("http://a.b/page?foo=bar&target=1&test=1")
url = new URL("http://a.b/page?foo=bar&target=1&test=1")
if (url.searchParams.get("foo") && url.pathname == '/page' {
# ...
}
也可以看看:
編輯
如果你必須使用正則表達式試試這個:
\/page(?=\?).*[?&]target=[^&\s]*(&|$)
說明:
\\/page(?=\\?)
- 匹配路徑(以/
然后page
開頭,然后查找?
) .*[?&]target=[^&\\s]*($|&)
匹配param name target
:
.*
) [?&]
之前是?
或&
$
)或另一個param( &
)結束 如果您正在尋找正則表達式,那么您可以使用:
/\/page\?(?:.*&)?target=[^&]*/i
RegEx詳細信息:
\\/page\\?
:匹配文字/page?
: (?:.*&)?
:匹配任意長度的可選文本,后跟&
target=[^&]*
:匹配文本target=
后跟0個或更多不是&
字符
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.