Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match single dot but not two dots?

Trying to create a regex pattern for email address check. That will allow a dot (.) but not if there are more than one next to each other.

Should match: [email protected]

Should not match: [email protected]

Now I know there are thousands of examples on internet for e-mail matching, so please don't post me links with complete solutions, I'm trying to learn here.

Actually the part that interests me the most is just the local part: test.test that should match and test..test that should not match. Thanks for helping out.

like image 334
Carbon6 Avatar asked May 20 '12 13:05

Carbon6


3 Answers

You may allow any number of [^\.] (any character except a dot) and [^\.])\.[^\.] (a dot enclosed by two non-dots) by using a disjunction (the pipe symbol |) between them and putting the whole thing with * (any number of those) between ^ and $ so that the entire string consists of those. Here's the code:

$s1 = "[email protected]";
$s2 = "[email protected]";
$pattern = '/^([^\.]|([^\.])\.[^\.])*$/';
echo "$s1: ", preg_match($pattern, $s1),"<p>","$s2: ", preg_match($pattern, $s2);

Yields:

[email protected]: 1
[email protected]: 0
like image 190
Junuxx Avatar answered Nov 15 '22 18:11

Junuxx


This seams more logical to me:

/[^.]([\.])[^.]/

And it's simple. The look-ahead & look-behinds are indeed useful because they don't capture values. But in this case the capture group is only around the middle dot.

like image 33
Mihai Stancu Avatar answered Nov 15 '22 16:11

Mihai Stancu


strpos($input,'..') === false

strpos function is more simple, if `$input' has not '..' your test is success.

like image 38
MajidTaheri Avatar answered Nov 15 '22 17:11

MajidTaheri