首页 > 解决方案 > 正则表达式语法仅匹配第一段

问题描述

我有许多 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

标签: regexmatchregex-lookaroundslookbehind

解决方案


尝试^在当前正则表达式模式中将起始锚点添加到初始后视:

(?<=^/)\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 /

推荐阅读