需要高级RegEx帮助

时间:2020-03-11 10:36:00

标签: javascript regex

我对使用regex替换字符串有一些不寻常的要求...请耐心等待。

我有一个输入字符串...

输入

<section className={some-class}>

Un-touched stuff here

</section>

<hr />

...并且我想替换字符串的一部分,以便输出最终像这样...

输出

<!-- some-class -->

Un-touched stuff here

<hr />

some-class 可以是任何东西,因此我需要匹配并替换本节的任一部分,类名。

另外<hr />代表我也不想触摸的任何其他html。

到目前为止,我有以下内容,但这并不完全正确,因为它也与<周围的/><hr />匹配

RegEx

\<section className\=|\{|\}|\<|\/|section|\>

3 个答案:

答案 0 :(得分:1)

希望以下内容对您有所帮助:

Test Regex here.

  1. <匹配<< / li>
  2. [^] *匹配下一个空格之前的所有内容(在这种情况下,它匹配section)
  3. [^ =] *?=匹配直到下一个=
  4. 的所有内容
  5. {匹配{
  6. ([[^}] *?)匹配并捕获所有内容,直到下一个}
  7. }>匹配}>
  8. ([[^ <] *)匹配所有内容,直到下一个<< / li>
  9. <\ /匹配<\ /
  10. \ 1与5(部分)中捕获的组匹配
  11. >匹配>
  12. \ s *匹配所有空白字符

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*/

See Regex Demo

  1. <section匹配<section
  2. \s+匹配一个或多个空格字符
  3. className=匹配className=
  4. {匹配{
  5. ([^}]+)捕获组1:一个或多个非}字符
  6. }匹配}
  7. \s*零个或多个空格字符
  8. >匹配>
  9. ([\s\S]*)捕获组2:任何类型(空白或非空白)的字符再增加零个
  10. <\/section>匹配</section>
  11. \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)

抱歉,我错过了有关我的问题的两个重要信息。

  • 输入实际上将具有多个部分标签
  • className是一个枚举,因此将在花括号内
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 />

相关问题