Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中通过正则表达式提取重复_Python_Regex_Pattern Matching - Fatal编程技术网

在Python中通过正则表达式提取重复

在Python中通过正则表达式提取重复,python,regex,pattern-matching,Python,Regex,Pattern Matching,我试图从通过正则表达式给出的大量数据中提取一些有用的数据。 示例字符串: test 1: hello op1 yviphf hello op2 vipqwe test 2: hello op3 hello op4 vipgt hello op5 zcv 上面包含2个测试编号,但有几个。我想提取op1、op2、op3、op4、op5以及相应的测试编号。每次测试中op的数量可能会有所不同。 以下是我尝试编写的模式,但没有帮助: test\s(\d+).*?(?:hello\s+(\S+).*?\n

我试图从通过正则表达式给出的大量数据中提取一些有用的数据。
示例字符串:

test 1:
hello op1 yviphf
hello op2 vipqwe
test 2:
hello op3
hello op4 vipgt
hello op5 zcv
上面包含2个测试编号,但有几个。我想提取op1、op2、op3、op4、op5以及相应的测试编号。每次测试中op的数量可能会有所不同。
以下是我尝试编写的模式,但没有帮助:

test\s(\d+).*?(?:hello\s+(\S+).*?\n)+

输出可以是列表的列表。主列表将第一个元素作为测试编号,第二个元素可能是包含所有op的列表。

我建议基于正则表达式的三步方法

  • 首先,使用
    r'test\s*(\d+)
    re.findall
    获取所有测试编号(这将仅获取编号列表,因为
    \d+
    子模式位于捕获组中)
  • 其次,使用
    test\s*\d+
    regex拆分输入字符串,以获得带有
    hello
    代码的子部分,并在每个非空块上运行
    hello\s+(\s+)
    (或
    (?m)^hello\s*(\s+)
    (如果
    hello
    从行开始)regex(同样,
    re.findall
    将只获取包含在捕获组中的
    \S+
    子匹配)
  • 将列表合并到元组列表中
:


结果:
[('1',['op1','op2']),('2',['op3','op4','op5'])]
您需要使用正则表达式吗

如果没有,则可以使用循环、strin比较和拆分:

data = {}
key = '_'
for linea in text.split('\n'):
    if "test" in linea:
        key = linea.split()[1][:-1]
        data[key]=[]
    else:
        _data_ = linea.split()[1]
        data[key].append(_data_)

print data
> {'1': ['op1', 'op2'], '2': ['op3', 'op4', 'op5']}

分两步进行:首先匹配完整的部分,然后为每个部分匹配op值。您需要使用正则表达式吗?您正在寻找
/s
标志吗?请参阅“可以”标记。您应该给出一个更好的示例字符串(更现实),因为很难回答。(ops看起来如何,每行的开头是否都有“hello”一词?)。如果您有大量数据,逐行工作会更好,也许您可以避免使用正则表达式并获得更快的结果。
data = {}
key = '_'
for linea in text.split('\n'):
    if "test" in linea:
        key = linea.split()[1][:-1]
        data[key]=[]
    else:
        _data_ = linea.split()[1]
        data[key].append(_data_)

print data
> {'1': ['op1', 'op2'], '2': ['op3', 'op4', 'op5']}