tags:

views:

71

answers:

3

Hello,

I am trying to replace a variable stored in another file using regular expression. The code I have tried is:

r = re.compile(r"self\.uid\s*=\s*('\w{12})'")
for line in fileinput.input(['file.py'], inplace=True): 
    print line.replace(r.match(line), sys.argv[1]), 

The format of the variable in the file is:

self.uid = '027FC8EBC2D1'

I am trying to pass in a parameter in this format and use regular expression to verify that the sys.argv[1] is correct format and to find the variable stored in this file and replace it with the new variable.

Can anyone help. Thanks for the help.

A: 

str.replace(old, new[, count])(old, new[, count]):

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

re.match returns either MatchObject or (most likely in your case) None, neither is a string required by str.replace.

SilentGhost
@Silent Ghost - I need to match the old string as it will change everytime someone enters in a new ID.
chrissygormley
@chrissy: well `str.replace` is not the right tool, so.
SilentGhost
+1  A: 

You need to use re.sub(), not str.replace():

re.sub(pattern, repl, string[, count])

Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. ... Backreferences, such as \6, are replaced with the substring matched by group 6 in the pattern.

...

In addition to character escapes and backreferences as described above, \g<name> will use the substring matched by the group named name, as defined by the (?P<name>...) syntax. \g<number> uses the corresponding group number;

Quick test, using \g<number> for backreference:

>>> r = re.compile(r"(self\.uid\s*=\s*)'\w{12}'")
>>> line = "self.uid = '027FC8EBC2D1'"
>>> newv = "AAAABBBBCCCC"
>>> r.sub(r"\g<1>'%s'" % newv, line)
"self.uid = 'AAAABBBBCCCC'"
>>> 
gimel
+2  A: 

You can use re.sub rather which will match the regular expression and do the substitution in one go:

r = re.compile(r"(self\.uid\s*=\s*)'\w{12}'")
for line in fileinput.input(['file.py'], inplace=True):
    print r.sub(r"\1'%s'" %sys.argv[1],line),
msanders
@msanders -- Thanks, this work's perfectly. +1
chrissygormley