Use Regular expression with fileinput
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]), 开发者_JS百科
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.
You can use re.sub
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),
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
instring
by the replacementrepl
. 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 bygroup 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'"
>>>
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
.
精彩评论