简体   繁体   English

用相同数量的字符替换正则表达式

[英]Replace regex with same number of chars

I need to replace the content found used a regex with the same number of characters using a character defined by me. 我需要使用我定义的字符,用相同数量的字符替换使用正则表达式找到的内容。

For example: 例如:

content: "abcdefghi*!?\"asd";

should becomes: 应该变成:

content: "-----------------";

This is my regexp: 这是我的正则表达式:

new RegExp("('|\").*('|\")", "gm")

And this is my attempt took from this answer ( Javascript Regex- replace sequence of characters with same number of another character ): 这是我从这个答案中尝试的( Javascript Regex-用相同数量的另一个字符替换字符序列 ):

source_text_safe = source_text.replace(new RegExp("('|\").*('|\")", "gm"), function ($0, $1, $2, $3) {
            return $1 + (new Array($2.length + 1).join("-")) + $3;
        });

But it doesn't work. 但这是行不通的。

Using it on this input: 在此输入上使用它:

::selected {
    color: purple
}
a {
    color: purple
}
a:hover {
    color: purple
}
a {
    color: purple
}
a:not("foobar\";{}omg") {
    content: 'example\';{} text';
    content: "example\";}{ text"
}
a {
    color: purple
}

I get this output: 我得到以下输出:

::selected {
    color: purple
}
a {
    color: purple
}
a:hover {
    color: purple
}
a {
    color: purple
}
a:not("-117) {
    content: '-150;
    content: "-184
}
a {
    color: purple
} 

If I use the regexp replacing the content with null it works fine, so is not a problem of regex. 如果我使用正则表达式将内容替换为null则可以正常工作,因此正则表达式不是问题。

Any help? 有什么帮助吗?

The replacement function requires three (catching) groups to be present in the regular expression but there are only two of them. 替换功能需要在正则表达式中包含三个(捕获)组,但是其中只有两个。 Therefore the $3 gets the offset of the match which is the unexpected number you get. 因此, $3获得匹配的偏移量,这是您得到的意外数字。 For details see Specifying a funciton as a parameter in Mozilla JS reference. 有关详细信息,请参见Mozilla JS参考中的将功能指定为参数

Use something like "('|\\")(.*)('|\\")" (3 groups) for your regular expression. 对正则表达式使用"('|\\")(.*)('|\\")" (3组)之类的东西。

Ok seems I've solved it... 好吧,看来我已经解决了...

source_text_safe = source_text.replace(new RegExp("('|\").*('|\")", "gm"), function ($0) {
    return (new Array($0.length + 1).join("-"));
});

Thanks for all the answers however. 感谢您的所有答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM