在python中使用正则表达式获取一组数字

ssm*_*ssm 7 regex python-3.x

假设我有以下字符串

string = "serial 7's 93-86-79-72-65 very slow, recall 3/3 "
Run Code Online (Sandbox Code Playgroud)

现在,我想在 Python 中使用正则表达式找到一组数字。请注意,数字前面必须"serial 7's"我尝试过的以下内容:

re.findall('(?<=serial 7\'s )(\d+, )', string)
re.findall('(?<=serial 7\'s )(\d+, )+', string)
Run Code Online (Sandbox Code Playgroud)

似乎没有任何效果。请注意,我们尝试提取的整数数量可能未知。我只想要具有特定模式的数字。不是其他可能分散在文本中的数字。

预期输出: ['93','86','79','72','65']

小智 5

另一种使用正则表达式的方法:

import re

string = "serial 7's 93-86-79-72-65 very slow, recall 3/3 "

regex = r"(?<=serial 7's) (\d+-?)+"

matches = re.finditer(regex, test_str, re.MULTILINE)

for match in matches:
    integers = match.group(0).strip().split("-")

print(integers) # ['93', '86', '79', '72', '65']
Run Code Online (Sandbox Code Playgroud)


Jvd*_*vdV 4

我的两分钱,你可以使用以下模式re.search

\bserial 7's\s(\d+(?:-\d+)*)
Run Code Online (Sandbox Code Playgroud)
import re
s = "serial 7's 93-86-79-72-65 very slow, recall 3/3 "
res = re.search(r"\bserial 7's\s(\d+(?:-\d+)*)", s)
if res:
    print(res.group(1).split('-')) # ['93', '86', '79', '72', '65']
else:
    print('No match')
Run Code Online (Sandbox Code Playgroud)

我会检查是否有任何匹配实际上首先发生,其中模式必须包含数字,如果有多个值,则由连字符分隔。既然您提到:“请注意,我们尝试提取的整数数量可能未知。我只想要具有特定模式的数字。”

  • \b- 单词边界。
  • serial 7's- 按字面意思匹配“serial 7's”。
  • \s+- 一个或多个空白字符。
  • (- 打开捕获组。
  • \d+- 至少匹配一个数字。
  • (?:-\d+)*- 非捕获组包含零次或多次连字符,后跟至少一个数字。
  • )- 关闭捕获组。

或者,可以使用regexmodule 并使用非固定宽度的正向后查找:

(?<=\bserial 7's\s+(?:\d+-)*)\d+
Run Code Online (Sandbox Code Playgroud)
import regex
s = "serial 7's 93-86-79-72-65 very slow, recall 77 3/3 "
lst = regex.findall(r"(?<=\bserial 7's\s+(?:\d+-)*)\d+", s)
print(lst) # ['93', '86', '79', '72', '65']
Run Code Online (Sandbox Code Playgroud)
  • (?<=- 积极回顾的开始。
    • \b- 一个词的边界。
    • serial 7's- 字面意思是“系列7”。
    • \s+- 多一个空白字符。
    • (?:- 打开非捕获组。
      • \d+-- 至少匹配一个数字,后跟连字符。
      • )*- 关闭非捕获组并匹配零次或多次。
    • )- 关闭积极的后视。
  • \d+- 至少匹配一个数字。