Train from London to Boston - match
Train from Boston to London
Train from Cardif to London
Bus from London to Paris - match
如果伦敦出现在任何其他具有正则表达式的城市之前,我该如何匹配?我可以使用JavaScript中的循环字符串匹配来完成它,但我认为正则表达式更好。
答案 0 :(得分:1)
获取包含London to
var str = `Train from London to Boston - match
Train from Boston to London
Train from Cardif to London
Bus from London to Paris - match`,
city = 'london';
console.log(
str.match(new RegExp('^.*\\b' + city + '\\sto\\b.*$', 'gmi'))
)

<强> Regex explanation here 强>
答案 1 :(得分:0)
试试这个
\bLondon(?=\s*to\b)
<强>解释强>
\
:逃脱一个特殊字符sample
(?=…)
:积极前瞻sample
\s
:&#34;空格字符&#34;:空格,制表符,换行符,回车符,垂直标签sample
*
:零次或多次sample
的Javascript
var re = /\bLondon(?=\s*to\b)/g;
var str = 'Train from London to Boston - match\nTrain from Boston to London\nTrain from Cardif to London\nBus from London to Paris - match';
var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}