使用正则表达式在一段时间之前获取所有内容

时间:2014-06-30 12:25:55

标签: python regex

我有一个看起来像这样的字符串:

STRING 1 160 Some descriptor information. /Uselessstuff.; STRING 161 274 Some other descriptor information. /Moreuselessstuff.; STRING 275 1070 Last descriptor info. /Lastuselesspart.

现在我想提取两个整数和随后的信息,然后忽略所有内容,直到字符串的结尾或分号。所以我希望最终得到:

[('1', '160', 'Some descriptor information'), ('161', '274', 'Some other descriptor information'), ('275', '1070', 'Last descriptor info')]

我试过了:

import re
s = "STRING 1 160 Some descriptor information. /Uselessstuff.; STRING 161 274 Some other descriptor information. /Moreuselessstuff.; STRING 275 1070 Last descriptor info. /Lastuselesspart."
re.findall(r'(\d+)\s(\d+)\s(\w+)', s)

但是,这仅提供以下内容:

[('1', '160', 'Some'), ('161', '274', 'Some'), ('275', '1070', 'Last')]

如何才能获得剩余的信息?

3 个答案:

答案 0 :(得分:3)

使用[^.]+代替\w+将选择一段时间内的所有字符。

答案 1 :(得分:3)

你的正则表达式是,

(\d+)\s(\d+)\s([^\.]*)

DEMO

你的python代码是,

>>> s = "STRING 1 160 Some descriptor information. /Uselessstuff.; STRING 161 274 Some other descriptor information. /Moreuselessstuff.; STRING 275 1070 Last descriptor info. /Lastuselesspart."
>>> m = re.findall(r'(\d+)\s(\d+)\s([^\.]*)', s)
>>> m
[('1', '160', 'Some descriptor information'), ('161', '274', 'Some other descriptor information'), ('275', '1070', 'Last descriptor info')]

<强>解释

  • (\d+)将一个或多个数字捕获到一个组中。
  • \s以上捕获的数字后面会有一个空格。
  • (\d+)再次将一个或多个数字捕获到第二组中。
  • \s后跟一个空格。
  • ([^\.]*)捕获任何不是文字点的字符零次或多次。

答案 2 :(得分:3)

您可以使用Character Class仅允许使用单词字符和空格。

>>> re.findall(r'(\d+)\s*(\d+)\s*([\w\s]+)', s)
[('1', '160', 'Some descriptor information'), ('161', '274', 'Some other descriptor information'), ('275', '1070', 'Last descriptor info')]

Working Demo

相关问题