使用正则表达式来匹配左边的内容

时间:2016-04-25 04:47:59

标签: regex

Train from London to Boston - match
Train from Boston to London
Train from Cardif to London
Bus from London to Paris - match

如果伦敦出现在任何其他具有正则表达式的城市之前,我该如何匹配?我可以使用JavaScript中的循环字符串匹配来完成它,但我认为正则表达式更好。

2 个答案:

答案 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

Regular expression visualization

答案 1 :(得分:0)

试试这个

\bLondon(?=\s*to\b)

Regex demo

<强>解释
\:逃脱一个特殊字符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.
}