除伦敦城外,Regex将删除伦敦

时间:2016-06-03 09:17:09

标签: javascript regex

除伦敦城外,我需要写一个正则表达式从列表中删除伦敦。提前谢谢。

输入

London Heathrow, London Gatwick, London City, London Southend, London Stanstead

输出

Heathrow, Gatwick, London City, Southend, Stanstead

2 个答案:

答案 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, '')
)




Regex explanation here.

Regular expression visualization

答案 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 "" ;
   }
});