使用regex在月经前获取所有信息?

2024-09-30 04:39:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我怎样才能得到截止到这段时间的其他信息?你知道吗


Tags: 字符串reinfo信息stringinformation整数some
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后跟一个空格。你知道吗
  • ([^\.]*)捕获任何非文字点的字符零次或多次。你知道吗

可以使用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

使用[^.]+而不是\w+将选择一个句点以内的所有字符。你知道吗

相关问题 更多 >

    热门问题