2011-08-18 103 views
3

我编写了一个程序从文件中读取注册表项。 和条目看起来是这样的:关于拆分字符串的问题

reg='HKEY_LOCAL_MACHINE\SOFTWARE\TT\Tools\SYS\exePath' #it means rootKey=HKEY_LOCAL_MACHINE, subKey='SOFTWARE\TT\Tools\SYS', property=exePath 

我想从文件中读取这个条目,并将其打入rootKey,子项和财产。 显然,我能做到这样:

rootKey = reg.split('\\', 1)[0] 
subKey = reg.split('\\', 1)[1].rsplit('\\', 1)[0] #might be a stupid way 
property = reg.rsplit('\\, 1)[1] 

也许条目是愚蠢的,但没有更好的办法来打破它分成几部分像上面?

+0

使用原始字符串---'reg.split(R '\')' – agf

+1

看起来有在这里回答过类似的问题 http://stackoverflow.com/questions/5833441/is-there -a-pure-python-library-for-parsing-a-windows-registry-file – severb

回答

4
import re 

t=re.search(r"(.+?)\\(.+)\\(.+)", reg) 
t.groups() 
('HKEY_LOCAL_MACHINE', 'SOFTWARE\\TT\\Tools\\SYS', 'exePath') 
+0

不错。谢谢。 – Alcott

2

如何进行以下操作?有没有必要打电话.split()这么多次,反正...

s = reg.split('\\') 
property = s.pop() 
root_key = s.pop(0) 
sub_key = '\\'.join(s) 
+0

是的,漂亮的工作人员。谢谢 – Alcott

0

我喜欢用partition超过split时,我可以,因为partition确保每个元组返回元素是一个字符串。

root_key, _, s  = reg.partition("\\") 
_, sub_key, property = s.rpartition("\\") # note, _r_partition