无法使用正则表达式 (?<!)
发布于 5 年前 作者 hkang 11077 次浏览 来自 问答

代码

// 去除样式中top|right|bottom|left
// 使用正则匹配
// ASCII表 | \55 - | \72 : | \73 ; |

let str = 'margin-top:12px;margin-bottom:12px;top:0;left:13px;';

str.replace(/(?<!\55)(top|right|bottom|left)\72\w+\73/g, '')

报错

当前解决方案

// 去除样式中top|right|bottom|left
// 使用正则匹配
// ASCII表 | \55 - | \72 : | \73 ; |
let str = 'margin-top:12px;margin-bottom:12px;top:0;left:13px;';
str.replace(/(\w+\55)?(top|right|bottom|left)\72\w+\73/g, function(res){
 if (/(\w+\55)(top|right|bottom|left)/.test(res)) {
   return res
 } else {
   return ''
 }
})

期望解决方案

只用一个正则表达式就能完成正则匹配

7 回复

…=w=,我可以啊~

而且这个正则表达在百度百科里有(https://baike.baidu.com/item/正则表达式/1700215?fr=aladdin

  • 在谷歌浏览器中是可以正常执行的

  • 在`开发者工具`中复制以上代码执行是不行的

我在谷歌上也是不可以的

let str2 = 'margin-top:12px;margin-bottom:12px;top:0;left:13px;';

    var a = str2.replace(/(<!\55top|right|bottom|left)\72\w+\73/g, '')  

试下这个

内个…好像这个表达式有问题呢

目前我的解决方案是有,但我想一行代码解决。

// 去除样式中top|right|bottom|left

// 使用正则匹配

// ASCII表 | \55 - | \72 : | \73 ; |

let str = 'margin-top:12px;margin-bottom:12px;top:0;left:13px;';

str.replace(/(\w+\55)?(top|right|bottom|left)\72\w+\73/g, function(res){

  if (/(\w+\55)(top|right|bottom|left)/.test(res)) {

   return res

  } else {
    return ''
  }
})

试了一下,是可以使用正则的,应该是你语法有错

回到顶部