【问题标题】:Why does my regex group quantifier not work?为什么我的正则表达式组量词不起作用?
【发布时间】:2016-11-30 21:50:03
【问题描述】:

我尝试为荷兰车牌 (kentekens) 编写一些正则表达式,the documentation 非常清楚,我只想检查它们的格式,而不是现在可能的实际字母字符。

My regex (regex101) 如下所示:

(([0-9]{1,2}|[a-z]{1,3})-([0-9]{2,3}|[a-z]{2,3})-([0-9]{1,2}|[a-z]{1,2})){8}/gi

然而这返回不匹配,而

([0-9]{1,2}|[a-z]{1,3})-([0-9]{2,3}|[a-z]{2,3})-([0-9]{1,2}|[a-z]{1,2}/gi

不过,我确实也喜欢检查总长度。

JS Demo sn-p

const regex = /([0-9]{1,2}|[a-z]{1,3})-([0-9]{2,3}|[a-z]{2,3})-([0-9]{1,2}|[a-z]{1,2})/gi;
const str = `XX-99-99
2​	1965​	99-99-XX ​
3​	1973​	99-XX-99​
4​	1978​	XX-99-XX ​
5​	1991​	XX-XX-99 ​
6​	1999​	99-XX-XX ​
7​	2005​	99-XXX-9​
8​	2009​	9-XXX-99​
9​	2006​	XX-999-X ​
10​	2008​	X-999-XX ​
​11	​2015	​XXX-99-X`;
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}`);
    });
}

【问题讨论】:

  • PHP 还是 javascript?
  • @chris85 项目是 PHP,但为了快速显示问题,我包含了一个 js 演示 :)

标签: php regex quantifiers


【解决方案1】:

这是因为在末尾添加的{8} 量词将作用于前一个表达式,在这种情况下是整个正则表达式,因为它用括号括起来。 See here 与此正则表达式匹配的内容。

要测试长度,请使用此正则表达式(?=^.{1,8}$)(([0-9]{1,2}|[a-z]{1,3})-([0-9]{2,3}|[a-z]{2,3})-([0-9]{1,2}|[a-z]{1,2})) 它使用前瞻来确保以下字符与^.{1,8}$ 匹配,这意味着整个字符串应包含1到8个字符,您可以根据需要进行调整.

【讨论】:

  • 有没有办法用正则表达式做到这一点,还是我注定要使用strlen
猜你喜欢
  • 1970-01-01
  • 2012-11-17
  • 1970-01-01
  • 2012-08-07
  • 1970-01-01
  • 2015-04-13
  • 2014-06-01
  • 2020-04-02
相关资源
最近更新 更多