简体   繁体   中英

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.

For example if I enter qwerty-123-123-123 that is okay.

If I enter something-123_world that is okay.

However if I enter qwerty-123-_whatever-something this should not match.

Current regex

My current regex matches the specific characters I want but I can't seem to figure out how to only allow 3 maximum. I thought {1,3} was the answer but that didn't seem to work. 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 .
  • (?:[-_.][^-_.]*){1,3} - one, two or three occurrences of
    • [-_.] - a - , _ or .
    • [^-_.]* - any 0+ chars other than - , _ and .
  • $ - end of string.

The other option apart from Regex would be to use 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'); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM