我是Python新手。我有一个包含以下内容的文件
#define VKU_BS_MAJOR_VERSION_S "2"
#define VKU_BS_MINOR_VERSION_S "0"
#define VKU_BS_BUILD_NUMBER_S "55"
我想提取2,0和55.之后我想增加这些值并将它们写回文件。但我根本无法获得它们。
我试过了:
buildInfoFile = open(buildInfoFilePath, "r")
content = buildInfoFile.read()
buildMajorRegex = re.compile("VKU_BS_MAJOR_VERSION_S \"(\\d+)\"", re.MULTILINE)
match = buildMajorRegex.match(content);
print(match)
打印
无
但是我已经在regex101检查了我的正则表达式并且工作正常。我做错了什么?
而且 - 增加价值并将其重新放回内容的最佳方式是什么?
答案 0 :(得分:0)
您可以使用regular expressions
和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']
答案 1 :(得分:0)
使用match = buildMajorRegex.search(content)
而match.group(1)
给出你的数字。
要使用match
,您的正则表达式必须完全匹配参数,如下所示:
buildMajorRegex = re.compile("#define VKU_BS_MAJOR_VERSION_S \"(\\d+)\"", re.MULTILINE)
match = buildMajorRegex.match(content)