我可以使用python“re.sub”而不是“sed”吗?

时间:2014-12-10 07:14:51

标签: python

我想将命令从一行转换为多行:

示例输入:

myprog  -library lib -topcell top -view layout

输出:

myprog \
          -library  lib\
          -topCell  top\
          -view  layout\

我可以使用" sed"如下:

echo $cmd | sed 's/\s-[a-zA-Z0-9]*\s/\\\n\t & /g'

但我无法通过python使用re.sub复制它。 我注意到re.sub不接受正则表达式作为第二个参数如下:

>>> re.sub(r'-[a-zA-Z0-9]*\s',r'[a-zA-Z0-9]*\s',cmd)

‘myprog [a-zA-Z0-9]*\\slib [a-zA-Z0-9]*\\stop [a-zA-Z0-9]*\\slayout'

你有解决方案吗?

2 个答案:

答案 0 :(得分:1)

x="myprog  -library lib -topcell top -view layout"
print re.sub(r"(?=-)",r"\\\n\t",x)

试试这个。

答案 1 :(得分:1)

在python中就像是,

>>> s = "myprog  -library lib -topcell top -view layout"
>>> print re.sub(r'(-[a-zA-Z0-9]*\s)',r'\\\n\t\1', s)
myprog  \
    -library lib \
    -topcell top \
    -view layout
>>> print re.sub(r'(-[a-zA-Z0-9]*\s)',r'\\\n\t \1 ', s)
myprog  \
     -library  lib \
     -topcell  top \
     -view  layout

在替换部件中的sed &中打印匹配的字符。在python中,我只使用了捕获组。