Regex test is getting failed in nodejs?

Viewed 180

I have two sentences which I need to compare and produce the result. The sentences are listed below.

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

Both the sentences are equal except for the val portion and it can be ignored. That's what below code is trying to do.

 //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);

It is getting failed. I don't have issues with val and pace, but if i add special characters in the sentences it gives me failure result only.

1 Answers

At the end of the script, this is the value of 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\#\}

And this is the value of msg2:

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

The first is not a valid regular expression for the second, because

  • \{\#val\#\} does not match 123 (use instead: var separators =/\\{\\#val\\#\\}|((\\s\*))/gi;);
  • msg2 characters should not be escaped.

See a working example below:

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'

Related