我正在定义一个正则表达式对象,然后在循环中匹配它。它只是偶尔匹配,确切地说 - 每隔两次。所以我创建了这个问题的最小工作示例。为什么Javascript正则表达式每次都匹配一次?
我在Opera和Firefox中试过这段代码。两者的行为相同:
>>> domainRegex = /(?:\.|^)([a-z0-9\-]+\.[a-z0-9\-]+)$/g;
/(?:\.|^)([a-z0-9\-]+\.[a-z0-9\-]+)$/g
>>> domainRegex.exec('mail-we0-f174.google.com');
Array [".google.com", "google.com"]
>>> domainRegex.exec('mail-we0-f174.google.com');
null
>>> domainRegex.exec('mail-we0-f174.google.com');
Array [".google.com", "google.com"]
>>> domainRegex.exec('mail-we0-f174.google.com');
null
>>> domainRegex.exec('mail-we0-f174.google.com');
Array [".google.com", "google.com"]
>>> domainRegex.exec('mail-we0-f174.google.com');
null
为什么会发生这种情况?此行为是否记录在案?除了在循环体内定义正则表达式之外,有没有办法解决这个问题?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec# Finding_successive_matches – Passerby
[为什么使用Javascript中的全局标志的RegExp会给出错误的结果?](http://stackoverflow.com/questions/1520800/why-regexp-with-global-flag-in-javascript-give-wrong-results ) – Bergi
@GDR这是因为[RegExp.lastIndex]发生的(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex?redirectlocale=en-US&redirectslug=JavaScript %2FReference%2FGlobal_Objects%2FRegExp%2FlastIndex)(_ read“description”section_)。 –