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

Python3如何用re.match从分号分隔命令行中完整匹配find命令

问题原因

你原来的正则使用了非贪婪匹配.*?,会在匹配到find命令内部-exec参数的转义分号\;后提前终止,没有识别到这个分号是find命令的内部语法,不是用来分隔不同命令的分隔符。

调整方案

核心逻辑是通过负向后行断言,匹配到真正用来分隔命令的未转义分号作为find命令的终止边界,调整后的代码如下:

import re

cmd = 'lsg <name>; cd <name>;find . -type f -exec grep -i <name> {} \; -print;lsg ; ps axwwl ' 
# (?<!\\); 匹配前面没有反斜杠转义的分号,也就是命令分隔符
pattern = r'.*(find.*?(?<!\\);)(.*$)' 
match = re.match(pattern, cmd)

if match:
    # 去除末尾的命令分隔分号即可得到完整find命令
    full_find_cmd = match.group(1).rstrip(';')
    print(full_find_cmd)

运行输出

find . -type f -exec grep -i <name> {} \; -print

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 14:15:04