首页 > 解决方案 > 用于匹配标签的 javascript 正则表达式

问题描述

考虑关注媒体查询。

 @media screen and (max-width: 768px) {
                .sd[data-s-e53caaf5-c227-4897-bb16-f957ee293e2f] {
                  max-width: calc(100% - 20px);
                }
              }

@media screen and (max-width: 480px) {
                .sd[data-s-e53caaf5-c227-4897-bb16-f957ee293e2f] {
                  max-width: calc(100% - 20px);
                }
              }

我有机器生成的 html 代码。我在代码中有超过 200 多个这样的媒体查询。我想删除所有这些。

所以我尝试了 VScode 正则表达式搜索

但我的正则表达式

 @media screen and \(max-width: 768px\)\s\{\n

只匹配所有媒体查询的第一行。让我知道如何使用正则表达式。建议是否有其他方法可以完成相同的任务。✌️

标签: regexvisual-studio-code

解决方案


您可以将文本与正则表达式匹配

^ *@media screen and \(max-width: \d{3}px\) *{ *\r?\n(?:.*\S.*\r?\n)+\r?\n?

并用空字符串替换匹配的文本。

演示

正则表达式引擎执行以下操作。

^ *               # match 0+ spaces at beginning of a line 
@media screen and \(max-width:  # match string 
\d{3}px\) *       # match 3 digits, 'px)' then 0+ spaces 
{ *\r?\n          # match '{', 0+ spaces, '\r' opt, '\n'
(?:.*\S.*\r?\n)   # match a line with 1+ non-whitespace chars
+                 # match above non-capture group 1+ times 
\r?\n?            # optionally match '\r' and '\n'

推荐阅读