Python3:re.match 单行命令列表中的命令,由 ; 分隔
Python3: re.match a command from a list of comands on a single line seperated by a ;
我正在尝试解析命令行,在命令之前或之后有 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
如有任何帮助,我们将不胜感激。
你可以使用
match = re.search(r'\bfind\s.*-exec\s.*\;?[^;]*', cmd)
if match:
print(match.group())
见regex demo。 详情:
\bfind
- 前面没有 letter/digit/_
的 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
我正在尝试解析命令行,在命令之前或之后有 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
如有任何帮助,我们将不胜感激。
你可以使用
match = re.search(r'\bfind\s.*-exec\s.*\;?[^;]*', cmd)
if match:
print(match.group())
见regex demo。 详情:
\bfind
- 前面没有 letter/digit/_
的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