Train from London to Boston - match
Train from Boston to London
Train from Cardif to London
Bus from London to Paris - match
如果倫敦出現在任何其他城市與正則表達式之前,我該如何匹配?我可以用JavaScript中的循環進行字符串匹配,但我認爲正則表達式更好。使用正則表達式匹配左側的東西
Train from London to Boston - match
Train from Boston to London
Train from Cardif to London
Bus from London to Paris - match
如果倫敦出現在任何其他城市與正則表達式之前,我該如何匹配?我可以用JavaScript中的循環進行字符串匹配,但我認爲正則表達式更好。使用正則表達式匹配左側的東西
獲取線路,其包括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'))
)
試試這個
\bLondon(?=\s*to\b)
說明:
\
:轉義特殊字符sample
(?=…)
:正向前查找sample
\s
: 「空白字符」:空格,製表,換行符,carr iage返回,垂直製表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.
}
'\ b'是爲了?如何使用此與JavaScript? – Jennifer
'\ b'是一個字的邊界,您可以使用'\ sLondon(?= \ s * to \ s)'來獲得相同的結果。 –
你嘗試過什麼?這是非常直接的,但你似乎沒有做任何努力來解決這個問題。 –
@EdCottrell我不知道布特正則表達式。 – Jennifer
你爲什麼要切換到正則表達式?你爲什麼認爲它更好? – qxg