在某个模式之后提取字符串并存储它们

时间:2014-07-09 19:43:05

标签: python regex file-io pattern-matching

我有一堆看起来像的输出:

 004400:  0x10000000 (268435456)
 004404:  0x0f010000 (251723776)
 004408:  0x0c018000 (201424896)
 00440c:  0x0c019000 (201428992)
 004410:  0x0b01a000 (184655872)
 004414:  0x0901a800 (151103488)
 004418:  0x0701aa00 (117549568)
 00441c:  0x0701aa80 (117549696)
 004420:  0x0701ab00 (117549824)
 004424:  0x0701ab80 (117549952)
 004428:  0x0701ac00 (117550080)
   .          .           .
   .          .           .
   .          .           .
 0047f4:  0x00000000 (0)
 0047f8:  0x00000000 (0)
 0047fc:  0x00000000 (0)

所以我想在地址(第一列)之后提取第二列中的内容(例如:0x10000000)。稍后我需要将它们写回来,如果它们可以存储在一个文件中然后作为列表回读那么会更好。我是Python的新手,想要找到一个易于使用的库。一些例子会很棒。非常感谢。

2 个答案:

答案 0 :(得分:2)

从索引1获取匹配的组,返回第二列。

(?<=:)\s*(0x.*?\b)

Demo


尝试这个

[^:]\s*(0x.*?\b)

Demo

说明

(?<=:)     Positive Lookbehind to match the character : literally
[^:]       match a single character that is not :
\s*        match any white space character 
.*?        matches any character (except newline) lazily
\b         assert position at a word boundary

示例代码:

import re
p = re.compile(ur'[^:]\s*(0x.*?\b)')
test_str = ...

re.findall(p, test_str)

还要查看此demo以对所有列进行分组。

答案 1 :(得分:0)

如果您只想要第二列的内容,则无需在此处使用正则表达式。你可以这样做:

with open('myfile.txt', 'r') as f:
    col2 = [line.split()[1] for line in f]

这将以列表col2为您提供第二列的内容。如果要将这些内容写入新文件,可以执行以下操作:

with open('outfile.txt', 'w') as f:
    for line in col2:
        f.write(line + '\n')