[英]Can I use python “re.sub” instead of “sed”?
我想將命令從一行轉換為多行:
輸入示例:
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'
但是我不能使用re.sub通過python復制它。 我注意到,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'
你有解決方案嗎?
x="myprog -library lib -topcell top -view layout"
print re.sub(r"(?=-)",r"\\\n\t",x)
嘗試這個。
在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中,我只是使用捕獲組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.