简体   繁体   中英

Regex that accepts only three specific letters, a hyphen , 6 or 9, then numbers

It must start with SEQ or ABC or MHT followed by '-' then 6 or 9 then followed by any number of digits.

example: SEQ-900000 (should pass)

$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;
}

This java method will work for your situation. (d+ stands for one or more decimals)

    public static boolean string_to_check(String string){
    return string.matches("(SEQ|ABC|MHT)-[69]\\d+");
    }

Use a start-of-line anchor ( ^ ), then a non-capturing group and pipe-separated branches to match your abbreviation, then a literal hyphen, then a 6 or a 9, then zero or more digits, then an end-of-string anchor ( $ ).

Code: ( Demo )

$string = 'SEQ-900000';

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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