简体   繁体   English

正则表达式以匹配特定模式

[英]Regex to match specific pattern

I am so bad at creating regex and I'm struggling with what I am SURE it's a simple stupid regex. 我在创建正则表达式方面非常不好,并且我为确保它是一个简单的愚蠢正则表达式而苦苦挣扎。

I am using PHP to do this match. 我正在使用PHP进行此匹配。 Here is what I have until now. 这是我到目前为止所拥有的。

Test string: 8848842356063003
if(!preg_match('/^[0-2]|[7-9]{16}/', $token)) {
    return array('status' => 'failed', 'message' => "Invalid token", 'token' => '');
}

The regex must comply to this: Start with 0-2 or 7-9 and have EXACTLY 16 characters. 正则表达式必须符合此要求:以0-2或7-9开头,并且必须有16个字符。 What am I doing wrong? 我究竟做错了什么? Because I get, as a match: 因为我得到了,作为匹配:

array(
  0 => 8
)

And I should get: 我应该得到:

array(
  0 => 8848842356063003
) 

By the way: I am using PHP Live Regex to test my regex string. 顺便说一句:我正在使用PHP Live Regex测试我的正则表达式字符串。

Thanks in advance, Ares D. 在此先感谢,战神D。

The regex must comply to this: Start with 0-2 or 7-9 and have EXACTLY 16 characters 正则表达式必须符合以下要求:以0-2或7-9开头,且必须有16个字符

You can put starting numbers in same character class and use end anchor after matching 15 more charaters: 您可以将起始数字放在相同的字符类中,并在匹配另外15个字符后使用结尾锚:

/^[0-27-9].{15}$/

If you want to match only digits then use: 如果只想匹配数字,请使用:

/^[0-27-9]\d{15}$/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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