What I need is to parce my projects' resource files and change its version number. I have a working JS script but I would like to implement it with python.
So, the problem stands in using re.sub:
version = "2,3,4,5"
modified_str = re.sub(r"(/FILEVERSION )\d+,\d+,\d+,\d+(\s)/g", ve开发者_如何转开发rsion, str_text)
I understand that because of using capturing groups my code is incorrect. And I tried to do smth like:
modified_str = re.sub(r"(/FILEVERSION )(\d+,\d+,\d+,\d+)(\s)/g", r"2,3,4,5\2", str_text)
And still no effect. Please help!
That's not the way to make multiline regexes in python. You have to compile the regex with the MULTILINE flag:
regex = re.compile(r"\bFILEVERSION \d+,\d+,\d+,\d+\b", re.MULTILINE)
Also, since you're using re.sub(), the FILEVERSION
part of your string will disappear if you don't specify it again in the replacement string:
version = "FILEVERSION 2,3,4,5"
modified_str = re.sub(regex, version, str_text)
To match other things than FILEVERSION
, introduce a capture group with an alternation:
regex = re.compile(r"\b(FILEVERSION|FileVersion|PRODUCTVERSION|ProductVersion) \d+,\d+,\d+,\d+\b", re.MULTILINE)
Then you can inject the captured expression into the replacement string using the backreference \1
:
version = r"\1 2,3,4,5"
modified_str = re.sub(regex, version, str_text)
Just want to summarize (probably will help someone):
I had to modify 4 lines in *.rc files, e.g.:
FILEVERSION 6,0,20,163
PRODUCTVERSION 6,0,20,163
...
VALUE "FileVersion", "6, 0, 20, 163"
VALUE "ProductVersion", "6, 0, 20, 163"
For the first two lines I used regexp given by Frederic Hamidi (thx a lot). For the last two I wrote another one:
regex_2 = re.compile(r"\b(VALUE\s*\"FileVersion\",\s*\"|VALUE\s*\"ProductVersion\",\s*\").*?(\")", re.MULTILINE)
And:
pass_1 = re.sub(regex_1, r"\1 " + v, source_text)
v = re.sub(",", ", ", v) #replacing "x,y,v,z" with "x, y, v, z"
pass_2 = re.sub(regex_2, r"\g<1>" + v + r"\2", pass_1)
Cheers.
精彩评论