简体   繁体   English

正则表达式以验证模式

[英]Regular expression to validate the pattern

The pattern I need is below: 我需要的模式如下:

  • MA should be the first two characters of a string MA应该是字符串的前两个字符
  • The third character should be hyphen ( - ) 第三个字符应为连字符( -
  • Characters 4 to 10 can be any numeric numbers ( 0-9 ) 字符4到10可以是任何数字( 0-9
  • The eleventh character should be hyphen ( - ) 第11个字符应为连字符( -
  • Characters 12 to 15 can be any numeric numbers ( 0-9 ) 字符12至15可以是任何数字( 0-9

Example: 例:

MA-1234567-1234

I have tried this: 我已经试过了:

/^(MA*)[0-9]{7}([0-9]{4})$/

Nearly there you were missing dashes for separators and you don't need the paranthesis if you don't want to extract any of the information. 几乎在其中缺少分隔符的破折号,并且如果您不想提取任何信息,则不需要括号。

Correct regex is: 正确的正则表达式为:

/^MA-[0-9]{7}-[0-9]{4}$/

Edit to satisfy new requirements To match both: CW291291 and MA-1234567-1234 编辑以满足新要求,以同时匹配:CW291291和MA-1234567-1234

Use the pipe symbol '|' 使用管道符号“ |” with both patterns to match either one: 两种模式都可以匹配其中一种:

/^CW[\d]{6}|MA-[\d]{7}-[\d]{4}$/

The Regex you were using is missing the dashes between character sets, try this: 您使用的正则表达式缺少字符集之间的破折号,请尝试以下操作:

/^MA-\d{7}-\d{4}$/

Note that to incorporate this with an input box you would need to test against this Regex on keyup, something like this: 请注意,要将其与输入框合并,则需要在键入时针对此Regex进行测试,如下所示:

var re = /^MA-\d{7}-\d{4}$/;
$('#code').keyup(function() {
    if (re.test(this.value)) {
        console.log('The code is valid...');
    }
});

Example fiddle 小提琴的例子

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

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