繁体   English   中英

使用正则表达式解析多行字符串

[英]Using regex to parse multiline string

这是我要解析的完整字符串:

Response
--------
{
  Return Code: 1
  Key        : <None>
  Files      : [
    {
      Return Code: 0
      Data       : 'Value' is 1
'Value' is two
This is third line of output
    }
  ]
}

这就是我希望解析后的文本看起来像的样子:

'Value' is 1
'Value' is two
This is third line of output

我已经尝试过re.findall()但是我无法得到我想要的。
这是一个python脚本,试图使用正则表达式进行解析。

import subprocess,re
output = subprocess.check_output(['staf', 'server.com', 'PROCESS', 'START', 'SHELL', 'COMMAND', "'uname'", 'WAIT', 'RETURNSTDOUT', 'STDERRTOSTDOUT'])
result = re.findall(r'Data\s+:\s+(.*)', output, re.DOTALL)[0]
print result

脚本输出

[root@server ~]# python test.py 
''uname'' is not recognized as an internal or external command,
operable program or batch file.

    }
  ]
}

选项1

如果要在Data:之后添加三行,则可以执行以下操作,将三行捕获到组1中:

match = re.search(r"Data\s*:\s*((?:[^\n]*[\r\n]+){3})", subject)
if match:
    result = match.group(1)

选项2

如果要在Data:之后的所有行,在包含}的第一行之前,将正则表达式更改为:

Data\s*:\s*((?:[^\n]*(?:[\r\n]+(?!\s*}))?)+)

使用以下正则表达式,您将找到所需的三个字符串。

请注意,这在很大程度上取决于响应的格式。

>>> import re
>>> response = """
Response
--------
{
  Return Code: 1
  Key        : <None>
  Files      : [
    {
      Return Code: 0
      Data       : 'Value' is 1
'Value' is two
This is third line of output
    }
  ]
}"""
>>> re.findall(r"('Value'.*)\n(.*)\n(.*)\n.*}",response)
[("'Value' is 1", "'Value' is two", 'This is third line of output')]

您还可以在这样的组中包括换行符:

>>> re.findall(r"('Value'.*\n)(.*\n)(.*\n).*}",response)
[("'Value' is 1\n", "'Value' is two\n", 'This is third line of output\n')]

取决于您以后如何处理。

更新

这个怎么样?

>>> re.findall(r"Data\s*:\s*(.*?)}",response,re.DOTALL)
["'Value' is 1\n'Value' is two\nThis is third line of output\n    "]

这将找到从第一个“值”到第一个“}”的所有内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM