Regex for 2 letters followed by 4 digits

前端 未结 5 1429
你的背包
你的背包 2020-12-22 13:31

The string should begin with \"S2\" followed by any 4 digits.

A matching string is \"S20165\".

I\'m trying with the following code, but it always echos OK ev

相关标签:
5条回答
  • 2020-12-22 14:12

    You need to match the start and end of the string too

    /^S2[0-9]{4}$/
    
    0 讨论(0)
  • 2020-12-22 14:13
    $string='S20104';
    if(preg_match('/^S2[0-9]{4}$/', $string)){
        echo 'OK';
    }
    else{
        echo 'NOT OK';
    }
    
    0 讨论(0)
  • 2020-12-22 14:13

    you missed the start^ and end$

    '/^S2[0-9]{4}$/'
    
    0 讨论(0)
  • 2020-12-22 14:17

    You have to use anchors:

    /^S2[0-9]{4}$/
    

    ^ matches the start of the string and $ matches the end of the string, so this will make sure that you check the complete string and not just a substring.

    You can also use \d instead of [0-9]. In PHP, as long as you do not use the 'u' pattern modifier, preg* functions are not Unicode aware, so the two are equivalent.

    0 讨论(0)
  • 2020-12-22 14:23

    The problem is that preg_match searches for a match anywhere inside the string.

    S2123456
    ^^^^^^
    matches
    

    You can anchor your regular expression using ^ (start of line) and $ (end of line):

    '/^S2[0-9]{4}$/'
    
    • See it working online: ideone
    • Read more about anchors: regularexpresssions.info/anchors.html
    0 讨论(0)
提交回复
热议问题