我对正则表达式不是很熟悉,并且遇到以下问题:

当运行regExp拆分字符串时,我得到很多未定义和“”以及结果。我已经尝试过使用“(?:”,这是我在stackoverflow和许多其他事情中的另一个答案中看到的。
然后,我使用array.filter函数将其删除,但我不想这样做。谁能帮我? (并向我解释为什么会这样)。

let values = line.split(/(\!=)|(<=)|(>=)|(==)|(\/\/)|(\/\*)|(\*\/)|(")|(=)|(<)|(>)|(\+)|(-)|(\*)|(\\)|(\()|(\))|;| /g);

return values.filter(value => {
    return value !== undefined && value !== "";
});


可以使用的字符串:

"int x = 7;" => ["int","x","=","7",";"]

"int x = 7 + 25 * 52" => ["int","x","=","7","+","25","*","52"]

"while( x != 0)" => ["while","(","x","!=","0",")"]

'if(idade > 70 && sexo == "masculino")'
    => ["if","(","idade",">","70","&&","sexo","==",""masculino"",")"]


谢谢!

最佳答案

原因是您在自己的捕获组中都有其他选择。仅实际匹配的捕获组将被填写,其余将为空。取而代之的是将捕获组放在所有替代方案周围。



line = "#include <stdio.h>";
let values = line.split(/(\!=|<=|>=|==|\/\/|\/\*|\*\/|"|=|<|>|\+|-|\*|\\|\(|\)|;| )/g);
console.log(values);

08-17 14:56