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

0 投票
2 回答
990 浏览
提问于 2025-04-18 07:17

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

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.

    }
  ]
}

2 个回答

0

使用下面这个正则表达式,你可以找到你想要的三个字符串。

注意,这个方法很依赖于响应的格式。

>>> 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    "]

这个方法会找到从第一个'Value'开始到第一个'}'结束的所有内容。

0

选项 1

如果你想要在 Data: 后面的三行内容,可以这样做,把这三行内容放到第一个组里:

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*}))?)+)

撰写回答