在Node.js中,正则表达式测试失败了?

3

我有两个句子需要比较并生成结果。这些句子如下所示。

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
我建议使用 https://regex101.com/ 进行测试,它非常有帮助。 - papillon
1个回答

0
在脚本的末尾,msg 的值为:
Hi\s*this\s*is\s*DLT\s*test\s*~ !\s*@ \#\s*\$\s*% \^\s*& \*\s*\(\s*\)\s* _\s*\-\s*\+\s*= \{\s*\[\s*\}\s*\]\s*\|\s*\\\s*: ;\s*" '\s*< \,\s*> \.\s*\?\s*/ End\s*\{\#val\#\}

这是 msg2 的值:

Hi this is DLT test ~ ! @ \# \$ % \^ & \* \( \)  _ \- \+ = \{ \[ \} \] \| \\ : ; " ' < \, > \. \? / End 123

第一个正则表达式不适用于第二个,因为

  • \{\#val\#\} 无法匹配 123(请使用:var separators =/\\{\\#val\\#\\}|((\\s\*))/gi;);
  • msg2 字符不应该被转义。

以下是一个可行的示例:

var msg = "Hi this is LT  ~ ! @ # $ % ^ & * ( )  _ - + = { [ } ] | \\ : ; \" ' < , > . ? / End {#val#}"
var msg2 = "Hi this is LT  ~ ! @ # $ % ^ & * ( )  _ - + = { [ } ] | \\ : ; \" ' < , > . ? / End 123"

//Trying to add escape character for special characters

msg = msg.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 upto 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)); //logs 'true'


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接