Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex matching if maximum two occurrences of dot and dash

Tags:

regex

php

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.

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.

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

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

like image 331
Zoon Avatar asked Jul 01 '11 11:07

Zoon


2 Answers

Is this matching your expectations?

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

See it here on Regexr

(?!^.*?([.-]).*\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.

like image 115
stema Avatar answered Oct 05 '22 23:10

stema


Use this: (?!^.*?([-.])(?:.*\1){2}.*$)^.*$

like image 24
Kirill Polishchuk Avatar answered Oct 06 '22 00:10

Kirill Polishchuk