仅匹配第一段的正则表达式语法
Regular expression syntax to match first segment only
我有 URL 的数量,我需要用 Regex
匹配第一个没有“/”的片段
该段可以是 xx 或 xx-xx。
我尝试使用前瞻和后视来做到这一点,但有时在 URL 中我还有另一个 2 个字母的片段。 (/ts/; /ca/) 我不要 /ts; /ca/ 他们匹配。
我只想要我的正则表达式中的第一段。有什么建议么?谢谢
https://regex101.com/r/Qy3nyI/1
(?<=\/)\w{2}(-\w{2})?(?=\/)
测试网址:
/en/home.aspx
/en-gb/ts/tc/home.aspx
/en-gb/home.aspx
/en-de/home.aspx
/de-de/home.aspx
/en/home.aspx
/en-fb/afspfas.aspx
/en-gb/ts/ca/anotherPage.aspx
尝试将起始 ^
锚点添加到当前正则表达式模式中的初始回顾:
(?<=^/)\w{2}(-\w{2})?(?=/)
^^ change is here
更新演示:
此模式表示:
(?<=^/) lookbehind and assert that what precedes is a leading /
\w{2}(-\w{2})? then match the country abbreviation text
(?=/) lookahead and assert that what follows is another /
我有 URL 的数量,我需要用 Regex
匹配第一个没有“/”的片段该段可以是 xx 或 xx-xx。
我尝试使用前瞻和后视来做到这一点,但有时在 URL 中我还有另一个 2 个字母的片段。 (/ts/; /ca/) 我不要 /ts; /ca/ 他们匹配。 我只想要我的正则表达式中的第一段。有什么建议么?谢谢
https://regex101.com/r/Qy3nyI/1
(?<=\/)\w{2}(-\w{2})?(?=\/)
测试网址:
/en/home.aspx
/en-gb/ts/tc/home.aspx
/en-gb/home.aspx
/en-de/home.aspx
/de-de/home.aspx
/en/home.aspx
/en-fb/afspfas.aspx
/en-gb/ts/ca/anotherPage.aspx
尝试将起始 ^
锚点添加到当前正则表达式模式中的初始回顾:
(?<=^/)\w{2}(-\w{2})?(?=/)
^^ change is here
更新演示:
此模式表示:
(?<=^/) lookbehind and assert that what precedes is a leading /
\w{2}(-\w{2})? then match the country abbreviation text
(?=/) lookahead and assert that what follows is another /