我有这个简单的代码行使用正则表达式,我想用空格替换字符串:
newAddress = myAddress.replace(/^.*?(ramp|arterial|majorroad|street &|highway &|highway|street|street &|street & highway|arterial & street|street & arterial|majorroad &|majorroad & ramp|ramp & majorroad|major road|highway & majorroad)\,/gi, '');
但是在变量中有这个:
Highway & Contrada Torremuzza, 95121 Catania CT
为什么它没有删除“高速公路&”一部分?
答案 0 :(得分:1)
它也试图匹配逗号,你需要使逗号可选或在这种情况下删除它。另外,除非你想删除前面的文本,否则删除字符串^
锚点的开头和.*?
newAddress = myAddress.replace(/(ramp|arterial|majorroad|street &|highway &|highway|street|street &|street & highway|arterial & street|street & arterial|majorroad &|majorroad & ramp|ramp & majorroad|major road|highway & majorroad)/gi, '');
答案 1 :(得分:1)
在我看来,你既不需要.*
也不需要逗号。 .*
将导致您替换字符串之前的所有内容。
试试这个:
(ramp|arterial|majorroad|street &|highway &|highway|street|street &|street & highway|arterial & street|street & arterial|majorroad &|majorroad & ramp|ramp & majorroad|major road|highway & majorroad)
或者,如果您喜欢花哨的优化:
(?:majorroad & )?ramp|(?:major r|(?:(?:ramp|highway) & )?majorr)oad|(?:highway|majorroad|street) &|(?:arterial & )?street|(?:street & )?(?:arterial|highway)
开玩笑吧。从理论上讲,这样更有效,但维护起来更难。
答案 2 :(得分:0)
我想我只是自己解决了:
newAddress = myAddress.replace(/^.*?ramp|arterial|majorroad|street|highway| &|\,/gi, '');
更短更高效...所以至少它会匹配单词加上&
干杯, 路易