我有两个句子需要比较并生成结果。这些句子如下所示。
var msg = "Hi this is LT ~ ! @ # $ % ^ & * ( ) _ - + = { [ } ] | \\ : ; \" ' < , > . ? / End {#val#}"
var msg2 = "Hi this is LT ~ ! @ # $ % ^ & * ( ) _ - + = { [ } ] | \\ : ; \" ' < , > . ? / End 123"
这两个句子除了“val”部分外是相等的,可以忽略不计。下面的代码就是试图做到这一点。
//Trying to add escape character for special characters
msg = msg.replace(/[-[\]{}()*+?.,\\^$|#]/g, '\\$&');
msg2 = msg2.replace(/[-[\]{}()*+?.,\\^$|#]/g, '\\$&');
//Adding space only if two {#val#} exists, else updating \\s* (can be many spaces or without spaces)
msg = msg.replace(/(^|.)\s($|.)/g, (x, g1, g2) => (x == "} {" ? x : g1 + "\\s\*" + g2));
//Replacing val with 1,29 (characters can be up to 29 in place of val)
var separators =/{#val#}|((\\s\*))/gi;
msg= msg.replace(separators, (x, y) => y ? y : ".(\\S{1,29})");
let regex = RegExp("^" + msg+ "$");
//Comparing two sentences
console.log(regex.test(msg2);
它正在失败。 我对val和pace没有问题,但如果我在句子中添加特殊字符,它只会给我失败的结果。
msg2
是你的测试字符串,为什么你也要转义它的特殊字符? - logi-kal