0

I am new for Python. I have a file with the following content

#define VKU_BS_MAJOR_VERSION_S "2"
#define VKU_BS_MINOR_VERSION_S "0"
#define VKU_BS_BUILD_NUMBER_S "55"

And i want to extract 2, 0 and 55. After it I want to increment these values and write them back to the file. But I simply can't obtain them.

I tried this:

buildInfoFile = open(buildInfoFilePath, "r")
content = buildInfoFile.read()
buildMajorRegex = re.compile("VKU_BS_MAJOR_VERSION_S \"(\\d+)\"", re.MULTILINE)
match = buildMajorRegex.match(content);
print(match)

Which prints

None

But I've checked my regular expression at regex101 and it works fine. What am I doing wrong?

And also - what is the best way to increment the values and put them back to 'content'?

Arman Oganesyan
  • 396
  • 3
  • 11
  • 1
    you are confusing match with search – njzk2 May 17 '16 at 18:59
  • 1
    `match` looks for a match starting at the *beginning* of the line; you might want to try the `search` method instead. – Mark Dickinson May 17 '16 at 18:59
  • See also http://stackoverflow.com/questions/35360740/regex-working-on-regex101-not-working-with-python, which was closed as a duplicate of http://stackoverflow.com/questions/180986/what-is-the-difference-between-pythons-re-search-and-re-match – Mark Dickinson May 17 '16 at 19:05

2 Answers2

0

You can achieve what you want by using regular expressions and findall.

import re

s1 = '#define VKU_BS_MAJOR_VERSION_S "2"'
s2 = '#define VKU_BS_MINOR_VERSION_S "55"'
s3 = '#define VKU_BS_B123UILD_N456UMBE789R_S "10"'

re.findall("\d+", s1)
#['2']

re.findall("\d+", s2)
#['55']

r.findall("\d+", s3)
#['123', '456', '789', '10']
dot.Py
  • 5,007
  • 5
  • 31
  • 52
0

Use match = buildMajorRegex.search(content) instead and match.group(1) gives your figure.

To use match, your regex has to match the argument exactly, like so:

 buildMajorRegex = re.compile("#define VKU_BS_MAJOR_VERSION_S \"(\\d+)\"", re.MULTILINE)
 match = buildMajorRegex.match(content)
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • Yes, as @njzk2 suggested I tried search instead of match. And what is the best way to increment the value and put it back? – Arman Oganesyan May 17 '16 at 19:11
  • read all the lines into a `list` (already done by `open()`), capture the numerical figures (already done), increment, then replace the figure in its corresponding item in the list. Finally, you write back all the values back to the file; an overwrite should do. – Moses Koledoye May 17 '16 at 19:24