如何用正则表达式匹配所有import语句并检查其后空行规范?
静态代码分析工具的import空行检查正则方案
问题背景
我正在用Python编写一款静态代码分析工具,需要实现一项检查:确保最后一条import语句后有一个空行。以下是待分析的代码示例:
import { component$, useClientEffect$, } from '@builder.io/qwik' import Swiper from 'swiper' import { Navigation, Pagination } from 'swiper' import { Image } from 'Base' import Button from '../Shared/Button' import Heading from '../Shared/Heading' const Portfolio = component$( ( { items, title, linkText, link } ) => {
示例中const Portfolio组件声明紧跟在最后一个import之后,不符合要求。我尝试过正则表达式(?<=import).*(?=from)但无效,同时需要考虑代码可能存在的不规范格式(如import前有空行、空格等),请问应该使用什么正则表达式来满足该需求?
解决方案
检测违规情况的正则表达式
要精准匹配最后一个import语句块后直接跟非空代码行的违规场景,可使用以下正则:
^(?:\s*import\b[\s\S]*?;\s*)+\s*(?!\s*$)\S
正则逻辑说明
^(?:\s*import\b[\s\S]*?;\s*)+:匹配一个或多个完整的import块,兼容各类不规范格式:- import语句前的任意空白(空行、空格、制表符都算)
- 多行拆分的import(比如带大括号换行的结构)
- import结尾的分号(兼容部分省略分号的代码风格)
- import语句后的任意空白字符
\s*(?!\s*$)\S:捕获import块后的内容,通过(?!\s*$)排除后续全是空白到文件结尾的情况,确保匹配到的是直接紧跟的非空白代码(比如const开头的组件声明)
Python 代码示例
用re.search()即可快速检测违规:
import re code = """import { component$, useClientEffect$, } from '@builder.io/qwik' import Swiper from 'swiper' import { Navigation, Pagination } from 'swiper' import { Image } from 'Base' import Button from '../Shared/Button' import Heading from '../Shared/Heading' const Portfolio = component$( ( { items, title, linkText, link } ) => {""" pattern = r'^(?:\s*import\b[\s\S]*?;\s*)+\s*(?!\s*$)\S' if re.search(pattern, code, re.MULTILINE): print("违规:最后一条import后缺少空行") else: print("符合要求:最后一条import后有空行")
验证合规性的正则(可选)
如果要直接验证代码是否符合要求(最后一个import后至少有一个空行),可以用:
^(?:\s*import\b[\s\S]*?;\s*)+\s*\n\s*\S
这个正则强制要求最后一个import块后至少有一个空行,再出现非空白代码。
内容的提问来源于stack exchange,提问作者Mohammad Miras
相关产品推荐
相关产品推荐

