【问题标题】:Python regular expressions - get numbers [duplicate]Python正则表达式 - 获取数字[重复]
【发布时间】:2016-09-14 00:44:44
【问题描述】:

我是 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 检查了我的正则表达式,它工作正常。我做错了什么?

还有 - 增加值并将它们放回“内容”的最佳方法是什么?

【问题讨论】:

标签: python regex


【解决方案1】:

您可以通过使用regular expressionsfindall 来实现您想要的。

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']

【讨论】:

    【解决方案2】:

    改用match = buildMajorRegex.search(content)match.group(1) 给出你的数字。

    要使用match,您的正则表达式必须完全匹配参数,如下所示:

     buildMajorRegex = re.compile("#define VKU_BS_MAJOR_VERSION_S \"(\\d+)\"", re.MULTILINE)
     match = buildMajorRegex.match(content)
    

    【讨论】:

    • 是的,正如@njzk2 建议的那样,我尝试搜索而不是匹配。增加价值并将其放回原处的最佳方法是什么?
    • 将所有行读入list(已经由open()完成),捕获数字(已经完成),递增,然后替换列表中相应项目中的数字。最后,将所有值写回文件;覆盖应该做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多