繁体   English   中英

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

[英]RegEx for matching an alphanumeric pattern with quantifier

我正在尝试将正则表达式中的数字限制在4到6之间,但是它不起作用

最小范围有效,但最大范围无效:

  • Some Text-1 =验证
  • Some Text-201901 =验证
  • Some Text-20190101 =在失败的地方通过了验证

现在,如果我在末尾添加$,则上述所有操作均无效。

码:

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

你想用

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

细节

  • ^ -字符串的开头
  • [AZ ]{3,} -三个或更多大写字母或空格
  • -连字符
  • [0-9]{3,6} -三到六位数
  • (?!\\d) -如果在当前位置的右边立即有一个数字,则匹配将使匹配失败。

我不太确定,我们可能希望通过和失败,但是根据您的原始表达式,我猜测这可能是我们可能希望以i标志开头的内容:

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

或没有i标记:

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

演示

测试

 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}`); }); } 

正则表达式

如果不需要此表达式,则可以在regex101.com中对其进行修改/更改。

RegEx电路

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

在此处输入图片说明

暂无
暂无

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

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