regex - 正则表达式语法仅匹配第一段
问题描述
我有许多 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 /
推荐阅读
- php - Plivo SMS 调试 - 获取特定消息的所有日志
- c# - 我需要一些关于 Web 浏览器窗口表单的帮助
- java - 如果完全通过对象而不是 FXML 完成,是否建议为 JavaFX UI 构建创建一个单独的类
- vba - 发送到共享联系人组
- r - 第 2 组变量(年龄和性别)并找到数量
- django - 在 django url 中出现循环导入错误
- python - 如何让 PyPI 自动安装依赖项
- javascript - 使用 jQuery 获取 DOM 节点,然后将它们输出为逗号分隔的字符串
- apache-kafka - Flink 作业抛出 SchemaException:错误计算字段“主题”的大小
- vue.js - 如何从扩展面板(Vuetify)中删除阴影?