3

I wrote a program to read a registry entry from a file. And the entry looks like this:

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

I want to read this entry from the file and break it into rootKey, subKey and property. Apparently, I can do it this way:

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

Maybe the entry is a stupid one, but any better way to break it into parts like above?

2
  • Use raw strings --- reg.split(r'\') Commented Aug 18, 2011 at 13:42
  • 1
    Looks like there is a similar question answered here stackoverflow.com/questions/5833441/… Commented Aug 18, 2011 at 13:49

3 Answers 3

4
import re

t=re.search(r"(.+?)\\(.+)\\(.+)", reg)
t.groups()
('HKEY_LOCAL_MACHINE', 'SOFTWARE\\TT\\Tools\\SYS', 'exePath')
Sign up to request clarification or add additional context in comments.

Comments

2

How about doing the following? There's no need to call .split() so many times, anyway...

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

Comments

0

I like to use partition over split when I can, because partition ensures each of the returned tuple elements is a string.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.