在编写正则表达式方面需要帮助

Posted

技术标签:

【中文标题】在编写正则表达式方面需要帮助【英文标题】:Need help in writing Regular expression 【发布时间】:2021-10-19 06:11:42 【问题描述】:

谁能帮我写正则表达式来匹配这种字符串

规则是:

    应该以 nl 开头 在 nl 和 contact 之间可以有或不能有一个参数(如 /abc/),但不能有(/abc/def/) 接触后什么都可以

示例:

nl/abc/contact --> 允许

nl/contact --> 允许

nl/abc/def/contact --> 不允许

nl/abc/contact/mno --> 允许

nl/abc/contactmno/ ---> 不允许

我尝试写一个 ("^nl(.?)/contact(.)$"),但它的问题是它允许任意数量的斜杠在 nl 和联系方式之间,我只想在两者之间最多加一个斜线

【问题讨论】:

【参考方案1】:

我会使用:

^nl(?:/[^/]+)?/contact(?:/[^/]+)*$

Demo

这个模式说匹配:

^            from the start of the path
nl           starts with "nl"
(?:/[^/]+)?  any zero or one path parameter following
/contact     /contact
(?:/[^/]+)*  followed by zero or more other path parameters
$            end of the input

【讨论】:

以上是关于在编写正则表达式方面需要帮助的主要内容,如果未能解决你的问题,请参考以下文章

php 正则表达式帮助,删除以 [caption id= 开头的字符串

如何为输入值编写正则表达式? [关闭]

如何编写匹配非贪婪的正则表达式? [复制]

python3 正则表达式

正则表达式初探

正则表达式匹配多个字符串之一