首页 > 解决方案 > 在正则表达式之前捕获字符

问题描述

我有一个关于我用 JavaScript 编写的正则表达式的快速问题。它是以下内容(?<=,)(.*)(?=:),它捕获了 和 之间,的所有内容:。但是,我希望它也能捕获逗号本身,例如。

So,<< this is what my regex captures at the moment>>: end会成为

So<<, this is what my regex captures at the moment>>: end.

我尝试在正则表达式中使用 a.之前,,但它似乎不起作用。

标签: javascriptregex

解决方案


如你所说 :

所以,<<这就是我的正则表达式此刻捕获的内容>>:end 会变成所以<<,这就是我的正则表达式此刻捕获的内容>>:end。

你可以这样使用replace

var str = `So,<< this is what my regex captures at the moment>>: end`;
var replace = str.replace(/(.*?)(,)(<<)(.*)/,"$1$3$2$4");
console.log(replace);


推荐阅读