我有一个字符串,我想获得一个数组,其中包含该字符串中与某个正则表达式条件不匹配的字符的索引(位置)。
这里的问题是,如果我这样写:
let match;
let reg = /[A-Za-z]|[0-9]/g;
let str = "1111-253-asdasdas";
let indexes = [];
do {
match = reg.exec(str);
if (match) indexes.push(match.index);
} while (match);
有用。它返回所有数字或字母字符的索引。但问题是,如果我试图做相反的事情,在正则表达式中使用负前瞻,就像这样:
let match;
let reg = /(?!([A-Za-z]|[0-9]))/g;
let str = "1111-253-asdasdas";
let indexes = [];
do {
match = reg.exec(str);
if (match) indexes.push(match.index);
} while (match);
它最终陷入无限循环。
我想要实现的是与第一种情况相同的结果,但使用负正则表达式,所以在这种情况下,结果将是:
indexes = [4, 8]; // which are the indexes in which a non-alphanumerical character appears
循环是错误的,还是正则表达式搞砸了?也许exec
不适用于负前瞻正则表达式?
我会理解正则表达式无法按预期工作(因为它可能格式错误),但我不理解无限循环,这让我认为这exec
可能不是实现我正在寻找的最佳方式为了。