How to find which portion is not matching using regular expression in NodeJS?

Viewed 57

I have a sentences like below, I need to match db defined messages with user messages and return what exactly is not matching. While matching the sentences we have two conditions,

  1. In place of xxx (defined in dbmsg), User can substitute and send anything ( 0- 5 ) chars limit or may not send any value. For example, user can send this "Hi, Stay calm Thanks" which is valid. ( Because for first 2 xxx xxx they didnt pass anything and for last xxx they have substituted calm ( 0- 5) which is valid )

  2. Other portion of the sentence should be exactly matching.

I have a regular expression,

 let dbmsg = "Hi xxx xxx, Stay xxx Thanks"
 let usermsg = "Hi qyz, Stay calm Thank you"

 let Stat = "ok"
 dbmsg = dbmsg.replace(/\s*(\xxx(?:\s*\xxx)*)/gi, (x, y) => 
            '.{0,' + ((y.match(/\xxx/gi) || ['']).length * 5 + (y.match(/\s/g) || '').length) + '}') 
 //Substituting xxx with .{0,5} where in place of xxx user can send up to max 5 //characters(any) 
 dbmsg= dbmsg.replace(/[ ]/g, '');
 usermsg = usermsg.replace(/[ ]/g, '');
 let regex = RegExp("^" + dbmsg+ "$", "i");
 if (!regex.test(usermsg)) {
   Stat = "Notok"
 }

Here we need to find out what is causing the failure, in case of error. In the above defined sentences, we should identify which of the following

1) xxx portion is not matching
2) Other portion of the sentence is not matching

I have tried the following in case of regular expression doesn't match,

 Like in place of xxx, there can be any number of characters ( .* ) and if both the sentences still doesnt match, there seems to be a problem with other portion of the sentence.  

            dbmsg = dbmsg.replace(/xxx/gi, ".*");
            let regex2 = RegExp("^" + dbmsg+ "$", "i");
            if (!regex2.test(usermsg)) {
                Status = "Other portion of the sentence is not matching"
            }
            else{
                Status = "xxx portion is not matching"
            }

From the given sentences dbmsg and usermsg only Thanks and Thank you are not matching ( Other portion is not matching)

The above method is working but its cpu utilization is more and it hangs the further requests. I suspect its because we are substituting .* . Is there any other approach which would consume minimal cpu time. Kindly help me on this?

0 Answers
Related