首页 > 解决方案 > 正则表达式测试在nodejs中失败了吗?

问题描述

我有两句话需要比较并产生结果。下面列出了这些句子。

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 和速度没有问题,但是如果我在句子中添加特殊字符,它只会给我失败的结果。

标签: javascriptnode.jsregex

解决方案


在脚本的末尾,这是 的值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'


推荐阅读