除伦敦城外,我需要写一个正则表达式从列表中删除伦敦。提前谢谢。
输入
London Heathrow, London Gatwick, London City, London Southend, London Stanstead
输出
Heathrow, Gatwick, London City, Southend, Stanstead
答案 0 :(得分:7)
对replace()
正则表达式使用 negative look ahead assertion 方法。
var str = 'London Heathrow, London Gatwick, London City, London Southend, London Stanstead';
console.log(
str.replace(/\bLondon\s(?!City\b)/gi, '')
)

答案 1 :(得分:3)
你的正则表达式是
/London City|London\s/g
首先匹配伦敦城市,然后匹配伦敦,然后匹配基于匹配值的匹配回调方法
尝试这一点
var input = "London Heathrow, London Gatwick, London City, London Southend, London Stanstead";
var output = input.replace(/London City|London\s/g, function(match){if (match == "London City") { return match } else { return "" }} );
console.log(output);

您可以扩展此正则表达式以包含其他名称(您不想替换它们),例如
/London Heathrow|London City|London\s/g //would not replace London Heathrow and London City
使用正则表达式构造函数
可以使其更具动态性var itemsNotToBeReplaced = ["London Heathrow", "London City"];
var regex = new RegExp( itemsNotToBeReplaced.push("London\s").join("|"), "g" );
input.replace(regex , function(match){
if (itemsNotToBeReplaced.indexOf(match) != -1)
{
return match ;;
}
else
{
return "" ;
}
});