[英]RegExp for expression sourrounded by special characters
有没有办法使用 RegExp 替换左侧被“/*”和右侧“*/”包围的 substring。 substring 可以包含任何内容(数字、下划线、特殊字符)
var string = "abc /*abcd_^&^djh:*/ <-abcd_.";
function replace(string, regexp, replacement="") {
return string.replaceAll(new RegExp(regexp), replacement);
}
let regexpReplacement; //The RegExp for a substring surounded by "/*" and "*/"
console.log(replace(string, regexpReplacement));
//Should output "abc <-abcd_."
使用惰性 0 无限量词的最佳时机。
Regex101 解释: https://regex101.com/r/JHxYKh/1
基本上:
匹配/*
,然后尽可能懒惰地匹配(使用*?
),以便下一个*/
不会被吸收,然后*/
。 全局标志允许 replaceAll 工作。
var string = "abc /*abcd_^&^djh:*/ <-abcd_."; function replace(string, regexp, replacement="") { return string.replaceAll(new RegExp(regexp), replacement); } let regexpReplacement = /\/\*.*?\*\//g; console.log(replace(string, regexpReplacement)); //Should output "abc <-abcd_."
如果您想要多行支持,请使用: https://regex101.com/r/mrPmYQ/1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.