【问题标题】:Regex that accepts only three specific letters, a hyphen , 6 or 9, then numbers只接受三个特定字母、连字符、6 或 9,然后是数字的正则表达式
【发布时间】:2021-12-30 19:51:57
【问题描述】:

它必须以 SEQ 或 ABC 或 MHT 开头,后跟“-”,然后是 6 或 9,然后是任意位数。

示例:SEQ-900000(应该通过)

$value = $data['firstname'];
// ^$ = anchors, [a-zA-Z ] = letters/spaces, {1,30} = 1-30 characters
$format = "/^[a-zA-Z ]{1,30}$/";
// If value does NOT match the format then it is invalid
if (!preg_match($format, $value)) {
    $feedback['firstname'] = 'Server feedback: Only 1-30 letters/spaces are permitted';
    $valid = false;
}

【问题讨论】:

  • 您是否尝试将您的第一句话翻译成正则表达式?这可以直译过来,也许只是添加一些组。例如,“必须以 SEQ 或 ABC 或 MHT 开头”可以翻译为 ^(SEQ|ABC|MHT)^ 是字符串的开头,| 是“或”)。其余的可以用同样的方式翻译。

标签: php regex string validation preg-match


【解决方案1】:

使用行首锚 (^),然后是非捕获组和管道分隔的分支来匹配您的缩写,然后是文字连字符,然后是 6 或 9,然后是零个或多个数字,然后是字符串尾锚 ($)。

代码:(Demo)

$string = 'SEQ-900000';

var_export(
    (bool)preg_match(
        '~^(?:SEQ|ABC|MHT)-[69]\d*$~',
        $string
    )
);
// true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-23
    • 2011-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 2016-03-27
    相关资源
    最近更新 更多