javascript - 正则表达式测试在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 和速度没有问题,但是如果我在句子中添加特殊字符,它只会给我失败的结果。
解决方案
在脚本的末尾,这是 的值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'
推荐阅读
- javascript - 咖喱/管道功能
- reactjs - ReactTable 数据未呈现
- php - 带有 Composer 的 GCP 无法运行 PHP,无法识别“应用程序”
- javascript - 敲除验证空字段在按钮单击时不起作用
- powershell - 用于更新现有用户的 Active Directory 属性的 Powershell 脚本
- c++ - 是否可以就地构造一个固定大小的数组作为函数参数?
- javascript - 用 addEventListener() 替换内联 onclick 函数
- rdf - 如何表达 RDF 三元数据?
- database - “唯一”:MongoDB 上的真实索引和批量插入
- youtube - 如何获取一段时间内 YouTube 视频的累计观看次数?