Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 正则表达式将“\”替换为“\”内部美元符号_Javascript_Regex - Fatal编程技术网

Javascript 正则表达式将“\”替换为“\”内部美元符号

Javascript 正则表达式将“\”替换为“\”内部美元符号,javascript,regex,Javascript,Regex,我有一根绳子 var str = "__Definition:__ $x_0$ is an _ordinary point_ of the ODE $L[y] = 0$"; 我想替换$$中的所有下划线,以便字符串 var str = "__Definition:__ $x\_0$ is an _ordinary point_ of the ODE $L[y] = 0$"; 如何在javascript中做到这一点?使用正则表达式进行此类解析活动不是一个好主意,但是,如果您想快速而肮脏的话 va

我有一根绳子

var str = "__Definition:__ $x_0$ is an _ordinary point_ of the ODE $L[y] = 0$";
我想替换
$$
中的所有下划线,以便字符串

var str = "__Definition:__ $x\_0$ is an _ordinary point_ of the ODE $L[y] = 0$";

如何在javascript中做到这一点?

使用正则表达式进行此类解析活动不是一个好主意,但是,如果您想快速而肮脏的话

var replaced = str.replace(/\$([^$]+)\$/, function(m, g) { 
  return '$' + g.replace(/_/, '\\_') + '$'; 
});

这可以在单个正则表达式替换调用中完成:

var str = "__Definition:__ $x_0$ is an _ordinary point_ of the ODE $L[y] = 0$";
var repl = str.replace(/_(?!(?:(?:[^$]*\$){2})*[^$]*$)/g, '\\_');
console.log(repl);
解释:表示匹配下划线字符后面不跟偶数个
$
符号。因此,2个
$
符号之间的
\
将匹配,外部将不匹配(因为这些符号后面是偶数个
$
符号)


现场演示:并不真正理解你想要什么,你的输出是不一致的,因为“是ODE的一个普通点”也在两个$signs之间,但在你的例子中,什么都没有发生,我不确定这是否是最好的解决方案,因此评论,但我想你可以使用反向引用来实现这一点。您可以尝试
str.replace(/([^$]*\$[^$]*)\([^$]*\$[^$]*)/g,\$1\\\\\$2')