我有一句话,需要和customer send message对比,返回是通过还是失败。 语句中包含{#val#},可替换为客户发送消息中的任意值。这里的条件是代替句子中的{#val#} => Customer message can contain anything within the limit of 5. {#val#} 是动态内容。消息的其他部分是静态内容。 在客户消息的静态内容中,我们可以忽略空格并与定义的句子进行比较。
但在客户发送消息的动态内容中,({#val#}) 空格是应该考虑的。例如,句子包含 {#val#}{#val#} 并且在 customer msg 中它应该被 nehradutta 而不是 nehra space dutta 替换,因为 2 {#val#}{#val#} 被连续放在定义的句子中.
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#}.
我需要形成一个正则表达式,在比较静态内容时避免空格,在比较动态内容时包含空格。
目前我的代码正在替换所有空格并进行比较。
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"
请帮助我,因为我是正则表达式的新手
最佳答案
var separators = ["#val#", "#VAL#", "#vaL#", "#vAl#", "#Val#"];
let sentence = "Hi {#VAL#}, Thank you {#val#} {#val#} for visting us";
// make all spaces optional. Except "} {".
regexString = sentence.replace(/(^|.)\s($|.)/g, (x, g1, g2) => (x == "} {" ? x : g1 + "\\s?" + g2));
// turn separators into .{0,5}
separators.forEach((str) => {
regexString = regexString.replace(new RegExp(`{${str}}`, "g"), ".{0,5}");
});
// input
var customermsg = "Hi asz, Thank you nehra dutta for visting us"; //Should Pass
var customermsg1 = "Hiasz, Thank you nehra dutta forvisting us"; //Should Pass
var customermsg2 = "Hi asz, Thank you nehradutta for visting us"; //Should Fail
let regex = RegExp("^" + regexString + "$");
console.log("REGEX ==>", regex);
console.log(regex.test(customermsg) ? "Pass" : "Fail", "==>", customermsg);
console.log(regex.test(customermsg1) ? "Pass" : "Fail", "==>", customermsg1);
console.log(regex.test(customermsg2) ? "Pass" : "Fail", "==>", customermsg2);
关于javascript - 如何在形成正则表达式来比较两个句子时仅忽略动态内容的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66004421/