Regular expression to match single dot but not two dots?

后端 未结 5 1526
广开言路
广开言路 2021-01-05 09:12

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: test.test@te

相关标签:
5条回答
  • 2021-01-05 09:35

    To answer the question in the title, I'd update the RegExp by Junuxx and allow dots in the beginning and end of the string:

    '/^\.?([^\.]|([^\.]\.))*$/'
    

    which is optional . in the beginning followed by any number of non-. or [non-. followed by .].

    0 讨论(0)
  • 2021-01-05 09:38
    strpos($input,'..') === false
    

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

    0 讨论(0)
  • 2021-01-05 09:43

    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.

    0 讨论(0)
  • 2021-01-05 09:45

    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 = "test.test@test.com";
    $s2 = "test..test@test.com";
    $pattern = '/^([^\.]|([^\.])\.[^\.])*$/';
    echo "$s1: ", preg_match($pattern, $s1),"<p>","$s2: ", preg_match($pattern, $s2);
    

    Yields:

    test.test@test.com: 1
    test..test@test.com: 0
    
    0 讨论(0)
  • 2021-01-05 09:48
    ^([^.]+\.?)+@$
    

    That should do for the what comes before the @, I'll leave the rest for you. Note that you should optimise it more to avoid other strange character setups, but this seems sufficient in answering what interests you

    Don't forget the ^ and $ like I first did :(

    Also forgot to slash the . - silly me

    0 讨论(0)
提交回复
热议问题