【问题标题】:Python3: re.match a command from a list of comands on a single line seperated by a ;Python3:重新匹配命令列表中的命令,单行以 ; 分隔
【发布时间】:2021-10-08 06:09:29
【问题描述】:

我正在尝试解析命令行,在命令之前或之后有 0 个或多个命令。

<name> 也是该行的一部分。

例子:

cmd = 'lsg <name>; cd <name>;find . -type f -exec grep -i <name> {} \; -print;lsg ; ps axwwl ' 
pattern = r'.*(find.*-exec.*\\;?.*?;?)(;*.*$)' 
match = re.match(pattern, cmd)

我得到的是:

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

我想要做的只是匹配find 命令,即:

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

任何帮助将不胜感激。

【问题讨论】:

    标签: python-3.x regex match


    【解决方案1】:

    你可以使用

    match = re.search(r'\bfind\s.*-exec\s.*\\;?[^;]*', cmd)
    if match:
        print(match.group())
    

    请参阅regex demo详情

    • \bfind - find 前面没有字母/数字/_ 的单词,然后
    • \s - 一个空格
    • .* - 除换行符以外的零个或多个字符,尽可能多
    • -exec - -exec 字符串
    • \s.* - 一个空格,然后是零个或多个字符,而不是换行符,尽可能多
    • \\ - 一个 \ 字符
    • ;? - 一个可选的 ; 字符
    • [^;]* - 除; 之外的零个或多个字符。

    Python demo

    import re
    rx = r"\bfind\s.*-exec\s.*\\;?[^;]*"
    text = r"lsg <name>; cd <name>;find . -type f -exec grep -i <name> {} \; -print;lsg ; ps axwwl "
    match = re.search(rx, text)
    if match:
        print (match.group())
    
    # => find . -type f -exec grep -i <name> {} \; -print
    

    【讨论】:

    • 太棒了!谢谢。
    • 完成,再次感谢。我对您的解决方案做了一个小的修改:``` rx = r"(.*)(\bfind\s.*-exec\s.*\\;?[^;]*)(.*)" ` ` 这样我就可以检索之前和之后的内容:``` match.group[1] match.group[2] match.group[3] ```
    • @cmora111 那部分对我来说不是很清楚。请注意,如果您打算匹配字符串中的 first find 单词,则需要在开头使用.*? 而不是.*,如果您需要使用.*需要到达最后一个find(这将是第二组的一部分。
    • 没问题。我只是在寻找如何获得整个 find 命令。由于 find 使用 ':' 来分隔 '-exec' 的结尾,并且命令分隔符是 ';'。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 2013-06-29
    • 2016-04-05
    相关资源
    最近更新 更多