我对使用regex替换字符串有一些不寻常的要求...请耐心等待。
我有一个输入字符串...
<section className={some-class}>
Un-touched stuff here
</section>
<hr />
...并且我想替换字符串的一部分,以便输出最终像这样...
<!-- some-class -->
Un-touched stuff here
<hr />
some-class 可以是任何东西,因此我需要匹配并替换本节的任一部分,类名。
另外<hr />
代表我也不想触摸的任何其他html。
到目前为止,我有以下内容,但这并不完全正确,因为它也与<
周围的/>
和<hr />
匹配
\<section className\=|\{|\}|\<|\/|section|\>
答案 0 :(得分:1)
希望以下内容对您有所帮助:
let str = `<section className={CLASS_A}>
Un-touched stuff here
</section>
<hr />
<section className={CLASS_B}>
Un-touched stuff here
</section>`;
let reg = /<([^ ]*)[^=]*?={([^}]*?)}>([^<]*)<\/\1>\s*/g
console.log(str.replace(reg, "<!-- $2 -->$3"));
答案 1 :(得分:0)
正则表达式:/<section\s+className={([^}]+)}\s*>([\s\S]*)<\/section>\s*/
<section
匹配<section
\s+
匹配一个或多个空格字符className=
匹配className=
{
匹配{
([^}]+)
捕获组1:一个或多个非}
字符}
匹配}
\s*
零个或多个空格字符>
匹配>
([\s\S]*)
捕获组2:任何类型(空白或非空白)的字符再增加零个<\/section>
匹配</section>
\s*
匹配零个或多个空格字符
let str = `<section className={xxxx}>
Un-touched stuff here
</section>
<hr />
`;
let regex = /<section\s+className={([^}]+)}\s*>([\s\S]*)<\/section>\s*/;
console.log(str.replace(regex, '<!-- $1 -->\n$2'));
答案 2 :(得分:0)
抱歉,我错过了有关我的问题的两个重要信息。
enum CLASS_A = "class-a"
enum CLASS_B = "class-b"
<section className={CLASS_A}>
Un-touched stuff here
</section>
<hr />
<section className={CLASS_B}>
Un-touched stuff here
</section>
我已经引用了上述解决方案,并感谢@Booboo和@ wp78de,并进行了一些小的调整,以下正则表达式似乎可以解决此问题。
https://regex101.com/r/hbkLp8/4
如果有更整洁的方法,请分享。
/<section\s+className\=\{([^>]*)\}>([\s\S]*?)<\/section>\s*/gm
<!-- class-a -->
Un-touched stuff here
<hr />
<!-- class-b -->
Un-touched stuff here
<hr />