简体   繁体   English

如何验证仅包含特定字母和数字的字符串?

[英]How to validate the string with only specific letter and number?

I want to validate the string containing characters A , B .我想验证包含字符AB的字符串。 X & Y . X & Y The character A & B must follow by the number but X, Y should not be.字符 A 和 B 后面必须跟数字,但 X、Y 不应该。

// correct 
"A11X",
"A45YA1X",
"A1XXA999YYA1",

// Not correct
"A1A1AAX12",
"1A1Y32A1",
"CA1A1",
"A1C1",

I am using following regex command.我正在使用以下正则表达式命令。

$flags = PREG_SET_ORDER;
        preg_match_all('/A|B(\d+)|.+/i', trim($command), $operations, $flags);

If the string is correct, it must return true otherwise it should return error message.如果字符串正确,则必须返回 true,否则应返回错误消息。

You may use this regex:你可以使用这个正则表达式:

^(?:[AB]\d+|[XY])+$

RegEx Demo正则表达式演示

  • This regex uses a non-capturing group that matches letter A or B followed by 1+ digits or using alternation matches letter X or Y .此正则表达式使用匹配字母AB后跟 1+ 数字或使用交替匹配字母XY的非捕获组。

  • This group is repeated 1 or more times to allow repetitions of this sub-pattern in entire string.该组重复 1 次或多次,以允许在整个字符串中重复此子模式。

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

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