解析一行文本以获取特定数字

时间:2010-06-25 18:22:52

标签: python parsing

我有" some spaces variable = 7 = '0x07' some more data"

形式的一行文字

我想解析它并从“some variable = 7”获得数字7。怎么能在python中完成?

3 个答案:

答案 0 :(得分:3)

我会使用更简单的解决方案,避免使用正则表达式。

在'='上拆分,并在您期望的位置获取值

text = 'some spaces variable = 7 = ...'
if '=' in text:
    chunks = text.split('=')
    assignedval = chunks[1]#second value, 7
    print 'assigned value is', assignedval
else:
    print 'no assignment in line'

答案 1 :(得分:2)

使用regular expression

基本上,你创建一个类似于"variable = (\d+)"的表达式,进行匹配,然后取第一个组,它将为你提供字符串7.然后你可以将它转换为int。

阅读上面链接中的教程。

答案 2 :(得分:0)

用于在字符串中查找数字的基本正则表达式代码段。

>>> import re
>>> input = " some spaces variable = 7 = '0x07' some more data"
>>> nums = re.findall("[0-9]*", input)
>>> nums = [i for i in nums if i]  # remove empty strings
>>> nums
['7', '0', '07']

查看python.org上的documentationHow-To

相关问题