如果最多出现两次点和破折号,则正则表达式匹配 [英] Regex matching if maximum two occurrences of dot and dash

查看:34
本文介绍了如果最多出现两次点和破折号,则正则表达式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个正则表达式来匹配最多包含 2 个破折号和 2 个点的任何字符串.不必有破折号或点,但如果有 3 个以上的破折号 3 个点,甚至 3 个以上的破折号和 3 个以上的点,则正则表达式必须与字符串不匹配.

I need a regular expression that will match any string containing at most 2 dashes and 2 dots. There does not HAVE to be a dash nor a dot, but if there is 3+ dashes or 3 dots or even both 3+ dashes and 3+ dots, then the regex must not match the string.

用于 PHP.
我知道使用 PHP 函数的简单替代方法,但它用于只允许使用正则表达式过滤的大型系统.

Intended for use in PHP.
I know of easy alternatives using PHP functions, but it is to be used in a large system that just allows filtering using regular expressions.

将匹配的示例字符串:
hello-world.com

Example string that will be MATCHED:
hello-world.com

不匹配的字符串示例:
www.hello-world.easy.com hello-world-i-win.com

Example string that will NOT be matched:
www.hello-world.easy.com or hello-world-i-win.com

推荐答案

这符合您的期望吗?

(?!^.*?([.-]).*\1.*\1.*$)^.*$

在 Regexr 上查看 此处

See it here on Regexr

(?!^.*?([.-]).*\1.*\1.*$) 是一个负面的前瞻.它匹配第一个 .- 将其放入捕获组 1,然后使用 hte 反向引用 \1 检查是否还有两个.一旦找到三个,表达式将不再匹配.

(?!^.*?([.-]).*\1.*\1.*$) is a negative lookahead. It matches the first .- put it in the capture group 1, and then checks if there are two more of them using hte backreference \1. As soon as it found three, the expression will not match anymore.

^.*$ 匹配从头到尾的所有内容,如果负前瞻不匹配.

^.*$ matches everything from start to the end, if the negative lookahead has not matched.

这篇关于如果最多出现两次点和破折号,则正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆