我有一个句子,如下所示
term = "How much new sales in new"
假设我收到一些建议,例如New York, New Delhi, Papua New Guinea
,我选择New York
。
choice = "New York"
现在,我需要确保与所选内容匹配的任何最新子字符串都替换为所选内容。
所以理想情况下,我的字符串现在应该变成
term = "How much new sales in New York"
所以这就是我所做的
terms = term.split(/s+/g)
choice_terms = choice.split(/s+/g)
terms.pop() //remove the last substring since this is what the user typed last
check_terms = terms
// get the latest instance of first term of the selection
if(user_choice_terms.length > 1) {
if(check_terms.lastIndexOf(user_choice_first_term) !== -1) {
last_index = check_terms.lastIndexOf(user_choice_first_term)
check_terms.splice(-last_index) //remove anything after the matched index
check_terms.push(...user_choice_terms) //add the selected term
return check_terms
}
}
但这似乎不是一个可靠的解决方案,我宁愿使用regex
.用户也可以像这样键入
term = "How much new sales in new yo"
在这里,我保证得到一个反对yo
New York
的建议,应该用New York
代替
是否有任何regex
解决方案可以确保将最新的子字符串匹配完全替换为选择?
注意:我正在使用jquery ui autocomplete
您可以创建一个模式,该模式将匹配choice
的所有可能前缀,将所有空格替换为s+
模式以匹配 1 个或多个空格,并在模式末尾添加$
以仅在字符串末尾匹配:
/N(?:e(?:w(?:s+(?:Y(?:o(?:r(?:k)?)?)?)?)?)?)?$/i
它将N
、Ne
、New
等与New
和York
之间任意数量的空格匹配,并且由于$
,只在字符串的末尾。
查看正则表达式演示
参见 JavaScript 演示:
const make_prefix = (string) => {
let s = string.charAt(0);
for (let i=1; i<string.length; i++) {
s += "(?:" + string.charAt(i);
}
for (let i=1; i<string.length; i++) {
s += ")?";
}
return s;
}
const term = "How much new sales in new yo";
const choice = "New York";
const regex = new RegExp(make_prefix(choice).replace(/s+/g, '\s+') + '$', 'i');
console.log(term.replace(regex, choice))
// => How much new sales in New York