const regex = /^([\s+]+7|\s?8)((\s?\(?\s?)[\s-]?\s?\d(\s?\)?\s?)){10}$/mg;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('^([\\s+]+7|\\s?8)((\\s?\\(?\\s?)[\\s-]?\\s?\\d(\\s?\\)?\\s?)){10}$', 'mg')
const str = `84951234567
+74951234567
8-495-1-234-567
8 (8122) 56-56-56
8-911-1234567
8 (911) 12 345 67
8-911 12 345 67
8 (911) - 123 - 45 - 67
+ 7 999 123 4567
8 ( 999 ) 1234567
8 999 123 4567
// выше - правильные, ниже - неправильные:
02
84951234567 позвать люсю
849512345
849512345678
8 (409) 123-123-123
7900123467
5005005001
8888-8888-88
84951a234567
8495123456a
+1 234 5678901
+8 234 5678901
7 234 5678901
`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
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}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions