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

标签 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')]

如何获取到该期间的剩余信息?

最佳答案

你的正则表达式是,

(\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 后跟一个空格。
  • ([^\.]*) 零次或多次捕获非文字点的任何字符。

关于python - 使用正则表达式在一段时间之前获取所有内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24490126/

相关文章:

javascript - 忽略相似匹配项的 Wildcad 选择器

python - nan、NaN和NAN有什么区别

python - 元素对于 selenium python 永远不可见,但在 selenium IDE 中工作正常

python - 如何为战舰中的舰船生成统计上可能的位置

c# - 查找具有模式的文件夹名称

regex - VB.NET 中带拆分的正则表达式

Java - 用于验证字符串是否为 StatsD 格式的正则表达式

ruby - 需要帮助使这个正则表达式正确

python - 使用 python3 脚本创建 unix 别名

python - flask-migrate:无法升级数据库,因为 "table does not exist"