如何使用可能的多行字符串解析列分隔的键值文本 [英] How to parse column separated key-value text with possible multiline strings

查看:149
本文介绍了如何使用可能的多行字符串解析列分隔的键值文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要解析以下文本:

First: 1
Second: 2
Multiline: blablablabla
bla2bla2bla2
bla3b and key: value in the middle if strting
Fourth: value

值是字符串或多行字符串,同时值可以包含"key:blablabla"子字符串.这种订阅应该被忽略(不解析为单独的键值对).

Value is a string OR multiline string, at the same time value could contain "key: blablabla" substring. Such subsctring should be ignored (not parsed as a separate key-value pair).

请帮助我使用正则表达式或其他算法.

Please help me with regex or other algorithm.

理想的结果是:

$regex = "/SOME REGEX/";
$matches = [];
preg_match_all($regex, $html, $matches);
// $mathes has all key and value parsed pairs, including multilines values

谢谢.

我尝试使用简单的正则表达式,但结果不正确,因为我不知道如何处理多行:

I tried with simple regexes but result is incorrect, because I don't know how to handle multilines:

$regex = "/(.+?): (.+?)/";
$regex = "/(.+?):(.+?)\n/";
...

推荐答案

您可以使用以下模式进行操作:

You can do it with this pattern:

$pattern = '~(?<key>[^:\s]+): (?<value>(?>[^\n]*\R)*?[^\n]*)(?=\R\S+:|$)~';

preg_match_all($pattern, $txt, $matches, PREG_SET_ORDER);

print_r($matches);

这篇关于如何使用可能的多行字符串解析列分隔的键值文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆