简体   繁体   English

RegEx用于将字母数字模式与量词匹配

[英]RegEx for matching an alphanumeric pattern with quantifier

I am trying to limit the digits between 4 and 6 in my regex but it is not working 我正在尝试将正则表达式中的数字限制在4到6之间,但是它不起作用

Minimum range works but the max range does not work: 最小范围有效,但最大范围无效:

  • Some Text-1 = validates Some Text-1 =验证
  • Some Text-201901 = validates Some Text-201901 =验证
  • Some Text-20190101 = passes the validation where it should fail Some Text-20190101 =在失败的地方通过了验证

Now if I add $ at the end then none of the above work. 现在,如果我在末尾添加$,则上述所有操作均无效。

Code: 码:

^[A-Z ]{3,}-\d{4,6}

You want to use 你想用

^[A-Z ]{3,}-[0-9]{3,6}(?!\d)

Details 细节

  • ^ - start of a string ^ -字符串的开头
  • [AZ ]{3,} - three or more uppercase letters or spaces [AZ ]{3,} -三个或更多大写字母或空格
  • - - a hyphen -连字符
  • [0-9]{3,6} - three to six digits [0-9]{3,6} -三到六位数
  • (?!\\d) - a negative lookahead that fails the match if, immediately to the right of the current location, there is a digit. (?!\\d) -如果在当前位置的右边立即有一个数字,则匹配将使匹配失败。

I'm not quite sure, what we might wish to pass and fail, however based on your original expression my guess is that this might be what we might want to start with with an i flag: 我不太确定,我们可能希望通过和失败,但是根据您的原始表达式,我猜测这可能是我们可能希望以i标志开头的内容:

^[A-Z ]{3,}-\d{1,6}$

or without i flag: 或没有i标记:

^[A-Za-z ]{3,}-\d{1,6}$

Demo 演示

Test 测试

 const regex = /^[AZ ]{3,}-\\d{1,6}$/gmi; const str = `Some Text-1 Some Text-201901 Some Text-20190101`; let m; while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } // The result can be accessed through the `m`-variable. m.forEach((match, groupIndex) => { console.log(`Found match, group ${groupIndex}: ${match}`); }); } 

RegEx 正则表达式

If this expression wasn't desired, it can be modified/changed in regex101.com . 如果不需要此表达式,则可以在regex101.com中对其进行修改/更改。

RegEx Circuit RegEx电路

jex.im visualizes regular expressions: jex.im可视化正则表达式:

在此处输入图片说明

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

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