如何用正则匹配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
相关产品推荐
相关产品推荐

