我有一个看起来像这样的字符串:
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([^\.]*)
你的 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/