[英]Check if string contains between 1 and 3 characters of .-_ anywhere in string
I am trying to create a regex that checks a string and will match a dot, dash or underscore. 我试图创建一个正则表达式来检查字符串,并将匹配点,破折号或下划线。 I only want it to allow a maximum of 3 otherwise it should not match the string.
我只希望它最多允许3个,否则它不应该与字符串匹配。
For example if I enter qwerty-123-123-123
that is okay. 例如,如果我输入
qwerty-123-123-123
可以。
If I enter something-123_world
that is okay. 如果我输入
something-123_world
没关系。
However if I enter qwerty-123-_whatever-something
this should not match. 但是,如果我输入
qwerty-123-_whatever-something
该值将不匹配。
My current regex matches the specific characters I want but I can't seem to figure out how to only allow 3 maximum. 我当前的正则表达式与我想要的特定字符匹配,但我似乎无法弄清楚如何只允许最多3个字符。 I thought
{1,3}
was the answer but that didn't seem to work. 我以为
{1,3}
是答案,但这似乎没有用。 I also had a look at ?=
positive lookups but not sure if that's correct / even able to get it to do what I want. 我也看过
?=
正向查询,但不确定那是正确的,甚至不能让它做我想要的事情。
You may use 您可以使用
/^[^-_.]*(?:[-_.][^-_.]*){1,3}$/
See the regex demo 见正则表达式演示
Details 细节
^
- start of string ^
-字符串的开头 [^-_.]*
- any 0+ chars other than -
, _
and .
[^-_.]*
-除-
, _
和之外的任何0+个字符.
(?:[-_.][^-_.]*){1,3}
- one, two or three occurrences of (?:[-_.][^-_.]*){1,3}
-出现一次,两次或三次
[-_.]
- a -
, _
or .
[-_.]
-a -
_
或.
[^-_.]*
- any 0+ chars other than -
, _
and .
[^-_.]*
-除-
, _
和之外的任何0+个字符.
$
- end of string. $
-字符串结尾。 The other option apart from Regex would be to use JavaScript! 除了Regex之外,另一个选择是使用JavaScript!
let str1 = 'qwerty-123-123-123'; let str2 = 'something-123_world'; let str3 = 'qwerty-123-_whatever-something'; const regex = /[._-]/g; let min = 1; let max = 3; function validate(txt) { var len = txt.match(regex).length; if(len >= min && len <= max) return true; return false; } console.log(validate(str1) ? 'Valid' : 'Invalid'); console.log(validate(str2) ? 'Valid' : 'Invalid'); console.log(validate(str3) ? 'Valid' : 'Invalid');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.