You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用正则匹配HTML中class属性内指定的CSS类名

匹配HTML class属性中特定CSS类名的正则方案

核心正则表达式

针对Ruby环境,推荐使用以下正则精准匹配class="..."属性内的目标CSS类名(以text-small为例):

/(?<=class=")(?:[^"]*\s)?text-small(?=(?:\s[^"]*)?")/

正则逻辑解析

  • (?<=class="):正向后顾断言,确保匹配位置严格位于class="之后,限定仅在class属性范围内查找。
  • (?:[^"]*\s)?:可选非捕获组,匹配任意数量非引号字符(即其他类名)加空格,适配class="other-class text-small"这类前置其他类的场景;?表示该组可省略,对应class="text-small"的纯目标类名场景。
  • text-small:替换为你实际需要查找的目标类名即可。
  • (?=(?:\s[^"]*)?"):正向前瞻断言,匹配空格加任意非引号字符(即后续其他类名)或直接到双引号,适配class="text-small other-class"这类后置其他类的场景;?表示该组可省略,对应class="text-small"的纯目标类名场景。

关键特性验证

  • ✅ 匹配合法场景:
    • class="text-small"
    • class="other-class text-small"
    • class="text-small other-class"
  • ❌ 排除非法场景:
    • 不匹配class="text-small-v2"(类名带后缀扩展的情况)
    • 不匹配class属性外的text-small(如正文文本中的出现)

Ruby代码示例

使用scan方法提取匹配项:

html = '<p class="text-small some-other-class">Hey here is some text-small too</p><span class="text-small-v2">hello there</span>'
matches = html.scan(/(?<=class=")(?:[^"]*\s)?text-small(?=(?:\s[^"]*)?")/)
puts matches.count # 输出:1

内容的提问来源于stack exchange,提问作者Danny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 19:05:21