【问题标题】:How to match text inside className using regex? [duplicate]如何使用正则表达式匹配 className 内的文本? [复制]
【发布时间】:2022-01-23 00:29:04
【问题描述】:

我想提取 className 属性中的字符串文本。例如,给定以下内容:

className="class1 class2" // should match: class1 class2
className='class1 class2' // should match: class1 class2
className={"class1 class2"} // should match: class1 class2
className={'class1 class2'} // should match: class1 class2
className={clsx("class1 class2")} // should match: class1 class2
className={clsx(foo, bar, "class1 class2", bar)} // should match: class1 class2
className={classname(foo, bar, "class1 class2", bar)} // should match: class1 class2
className={anything(foo, bar, "class1 class2", bar)} // should match: class1 class2
className={`flex-col flex ${className}`} // should match: flex-col flex

我想到的最好的是:

// this also matches the pref/suffix quotes. e.g. "class1 class2"
(?:\b(?:class(?:Name)?|tw)\s*=\s*(?:(?:{([\w\d\s!?_\-:/${}()[\\]\"'`,]+)})|([\"'`][\w\d\s_\-:/]+[\"'`])));
// close to working example here, but not sure what Im doing wrong
(?:[\\\"'\\`]([.wds_\-:/${}()\\[\\]\\]+)[\\\"'\\`])

游乐场:https://regex101.com/r/vc7Hbc/1

【问题讨论】:

  • 不要尝试使用正则表达式解析 HTML,使用 DOM 解析器。
  • @Barmar 这不适用于客户端。正则表达式是我正在使用的 VS 扩展的一部分。本质上,使用仅选择类名的正确正则表达式将允许扩展以正确的顺序转换文本。

标签: javascript regex


【解决方案1】:

我建议这个正则表达式

(?:class(?:Name)?|tw)\s*=\s*{?.*(["'`])(.*?)(?:\s\$.*)?\1.*}?

测试:https://regex101.com/r/sJomfs/1

要查找class=className= 使用的(?:class(?:Name)?|tw)\s*=\s* 正则表达式。

在定义正则表达式末尾的=.*}? 之后管理大括号{?.*

使用(["'``])\1 检测引号。 \1 指的是第一个匹配的括号,表示引用应该以开始的符号结束。

所需的类与(.*?) 部分匹配。 .*.*? 的区别在这里讨论:What is the difference between .*? and .* regular expressions?

要排除 $ 符号部分 (?:\s\$.*)? 使用正则表达式。

【讨论】:

    猜你喜欢
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 2010-12-07
    相关资源
    最近更新 更多