tags:

views:

46

answers:

2

Hello guys,

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", version, 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!

+3  A: 

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)
Frédéric Hamidi
Thanks a lot, that works for me! But what about capturing groups? I replace 4 lines in RC (FILEVERSION, PRODUCTVERSION, FileVersion and ProductVersion) with one version number. So, its preferable to have 4 regexps and only one version_variable. as far as i understand - i need cap.groups for that. Thanks.
Dalamber
You can even do it with one regex. See my edited answer.
Frédéric Hamidi
A: 

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.

Dalamber