如何使用regex从以null结尾的字符串中提取键值对


How to extract key value pairs from null terminated strings with regex?

我从服务器的请求中得到了一些键值对数据,如下所示。

Key0Value0Key20Value20Key30Value30

我已将空字符替换为"0"。我不知道如何使用正则表达式来实现这一点。

我想要像这个这样的值

[Key]  => Value
[Key2] => Value2
[Key3] => Value3

这是我能得到的最接近的

0(.+?)0(.+?)0(?=0|$)

只有当每个键对值前后都有一个"0"时,它才有效。正如它所做的那样,它会向前看,看看是否能找到第二个"0"或字符串的末尾。

所以我遇到的问题是,密钥对的值用同一个分隔符分隔,所以你无法区分它们。。。而不知道数据总是以键开始,以值结束。交替模式。

所以。。。简而言之,当正则表达式中的键值对具有相同的分隔符时,是否可以将它们分开?

在没有标记语言的情况下,为您提供一个可以适应任何其他语言的Javascript解决方案:

var re = /([^0]+)0([^0]+)/g,
    matches = {},
    input = "Key0Value0Key20Value20Key30Value30";
while (m = re.exec(input)) matches[m[1]] = m[2];
console.log(matches);
//=> Object {Key: "Value", Key2: "Value2", Key3: "Value3"}

编辑:PHP解决方案

$re = "/([^0]+)0([^0]+)/"       
$input = 'Key0Value0Key20Value20Key30Value30'
$matches = array();
preg_match_all($re, $input, $matches);    
$output = array_combine($matches[1], $matches[2]);
print_r($output); 
//=> Array( [Key] => Value [Key2] => Value2 [Key3] => Value3

如果我很好地理解了你的问题,你想要得到的是:

Key0Value (pair 1)
Key20Value2 (pair 2)
Key30Value3 (pair 3)

然后通过移除中间的零,从每对中提取密钥和值,对吗?

您可以使用此正则表达式来获取对:(.+?0.+?)0|0(.+?0.+?)