如何在 或我后找到空格? 它在javascript中不起作用:
\s(?<=at|me)
答案 0 :(得分:1)
答案 1 :(得分:0)
您可以使用几个more or less magic tricks来模拟lookbehind,例如:
s = "space after at or me !"
// "space after at or me !"
String.prototype.reverse = function () { return this.split('').reverse().join('') }
s.reverse().replace(/ (?=ta|em)/g, "@").reverse()
// "space after at@or me@!"
也就是说,在像你这样的简单案例中你可以捕获前面的组并将其粘贴到替换组中:
s.replace(/(at|me) /g, "$1@")
// "space after at@or me@!"
答案 2 :(得分:0)
JavaScript本身不支持look-behind(但ES6正则表达式)。
您可以使用全局RegExp
对象的属性来解决这个问题:
var input = "How can I match the space after at or me in JavaScript?";
var regex = /\b(at|me)(\s)/ig;
var match, before, after;
while (regex.exec(input)) {
before = RegExp.leftContext + RegExp.$1;
match = RegExp.$2;
after = RegExp.rightContext;
console.log(before);
console.log(match);
console.log(after);
}
将记录
"How can I match the space after at" " " "or me in JavaScript?" "How can I match the space after at or me" " " "in JavaScript?"