简体   繁体   English

如何加速 CSS 文件中的正则表达式 findall

[英]How to speed up regex findall in a CSS file

I'm using regex to find all selectors in CSS files and sometimes, it loads for minutes.我正在使用正则表达式来查找 CSS 文件中的所有选择器,有时它会加载几分钟。 After looking at the files, I found out that the sourceMappingURL is really large and cause the issue:查看文件后,我发现 sourceMappingURL 非常大并导致问题:

sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndvb2QuZnVsbC5taW4uY3NzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJpQkFFQSw4QkFBOEIsU0FBUyxPQUFPLGlCQUFpQixPQUFPLEtBQUssb0JBQW9CLEtBQUssUUFBUSxPQUFPLEVBQUUsU0FBUyxtQkFBbUIsSUFBSSxRQUFRLFdBQVcsT0FBTyxvQkFBb0IsNEJBQTRCLE9BTyxL...

Here's the full CSS file: https://jsfiddle.net/jj_jaq/32d7hpc0/3/这是完整的 CSS 文件: https : //jsfiddle.net/jj_jaq/32d7hpc0/3/

Here's my regex:这是我的正则表达式:

selectors = re.findall(r'([.#\w][-\w,\s.]+)(\{(.*?)\})', content)

Is there a way to speed up my regex?有没有办法加快我的正则表达式?

You may tell the regex engine to anchor the matches at left-hand word boundaries.您可以告诉正则表达式引擎将匹配锚定在左侧单词边界处。 However, just adding \\b won't work as the first char you want to match can also be a .但是,仅添加\\b将不起作用,因为您要匹配的第一个字符也可以是. or # that are non-word chars.#是非单词字符。

Use

[.#]?\b([-\w,\s.]+){([^{}]*)}

See the regex demo where [.#]?看到正则表达式演示在哪里[.#]? matches an optional .匹配一个可选的. or # before the word boundary check.#在单词边界检查之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM