Thursday 18 March 2021

How to ignore spaces only for dynamic content while forming an regular expression to compare two sentences?

I have a sentence, and I need to compare it with customer send message and return whether it has been passed or failed. Sentence contains {#val#}, which can be replaced by any values in the customer send messages. Condition here is in place of {#val#} in a sentence => Customer message can contain anything within the limit of 5. {#val#} is the dynamic content. Other part of the messages are static content. In static content of the customer message, we can ignore the space and compare with the sentence defined.

But in dynamic content of the customer send messages,({#val#}) spaces should be considered. For example, sentence contains {#val#}{#val#} and in customer msg it should be replaced by nehradutta not nehra space dutta since 2 {#val#}{#val#}s are continuosly put up in the defined sentence.

 var sentence = "Hi {#val#}, Thank you {#val#} {#val#} for visting us"

var customermsg = "Hi asz, Thank you shaky dutta for visting us" //Should Pass as sentence and customer msg  are matching 

var customermsg1 = "Hiasz, Thank you shaky dutta forvisting   us" //Should Pass as sentence and customer msg  are matching ( Ignoring the space in static portion ) 

var customermsg2 = "Hi asz, Thank you nehra      dutta for visting us" //Should Fail since there is lot of space between the dynamic content {#val#} => (nehra     dutta) places.  Should contain single space since the sentence has {#val#}space{#val#}.

I need to form a regular expression, which would avoid spaces while comparing static content and include spaces while comparing dynamic content.

Currently my code is below replacing all the spaces and comparing.

var separators = ['#val#','#VAL#','#vaL#','#vAl#','#Val#'];
var regexStr = sentence.replace(/[\ ]/g,''); 
var customermsg = customermsg.replace(/[\ ]/g,'');
separators.forEach(str => { 
   regexStr = regexStr.replace(new RegExp(str, 'g'), '.{0,5}')  
}) 
var regex = new RegExp(`^${regexStr }$`,"i")
 if (!customermsg.match(regex))       
   Status = "Fail" 
 else    
   Status = "Pass" 

Kindly help me on this as I'm new to regular expression



from How to ignore spaces only for dynamic content while forming an regular expression to compare two sentences?

No comments:

Post a Comment