2017-02-28 34 views
-3

我試圖從文件中對變量進行regex;這些文件看起來像:正則表達式並重命名python中的變量

...unknown lines... 
    @ legend hgap 1 
    @  s0 legend "foo" 
    @  s2 legend "bar" 
    ...unknown lines 

一個簡單的正則表達式是

^@[ \t]*s\d*[ \t]*(legend)[ \t]*[A-z0-9"_]* 

符合我的需要。

但現在,我需要重新命名S0(是的,資本S),以foo和S1到bar。 我該怎麼做?

回答

0

,如果你的意思是改變S0爲foo,這裏有一個提示:

>>> s = re.sub('s0','foo',' @  s0 legend "foo"') 
>>> print(s) 
    @  foo legend "foo"