Tôi đang xác định đối tượng regex và sau đó đối sánh nó trong một vòng lặp. Nó chỉ phù hợp với đôi khi, để được chính xác - mỗi lần thứ hai. Vì vậy, tôi tạo ra một mẫu làm việc nhỏ nhất của vấn đề này.Tại sao Javascript Regex khớp với nhau mỗi lần thứ hai?
Tôi đã thử mã này trong Opera và Firefox. Hành vi này giống nhau ở cả hai:
>>> 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
Tại sao điều này xảy ra? Hành vi này có được ghi lại không? Có cách nào xung quanh, khác hơn là xác định regex bên trong vòng lặp cơ thể?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec# Finding_successive_matches – Passerby
có thể trùng lặp của [Tại sao RegExp với cờ toàn cầu trong Javascript cho kết quả sai?] (Http://stackoverflow.com/questions/1520800/why-regexp-with-global-flag-in-javascript-give-wrong-results) – Bergi
@GDR điều này xảy ra vì [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) (_ đọc "mô tả" section_). –