使用特定的Regex规则将单个字符串拆分为一个数组


Split a single string into an array using specific Regex rules

我正在处理一个包含多对数据的字符串。每对由;符号分隔。每对包含一个数字和一个字符串,由=符号分隔。

我认为这很容易处理,但我发现字符串对的一半可以包含=;符号,这使得简单的拆分不可靠。

下面是一个有问题的字符串示例:

123=one; two;45=three=four;6=five;

为了正确处理这个问题,我需要将其拆分为一个数组,如下所示:

'123', 'one; two'
'45',  'three=four'
'6',   'five'

我有点穷途末路,所以任何帮助都很感激。

更新:

感谢大家的帮助,这就是我目前的处境:

$input = '123=east; 456=west';
// split matches into array
preg_match_all('~('d+)=(.*?);(?='s*(?:'d|$))~', $input, $matches);
$newArray = array();
// extract the relevant data
for ($i = 0; $i < count($matches[2]); $i++) {
    $type   = $matches[2][$i];
    $price  = $matches[1][$i];
    // add each key-value pair to the new array
    $newArray[$i] = array(
        'type'      => "$type",
        'price'     => "$price"
    );
}

哪个输出

Array
(
    [0] => Array
        (
            [type] => east
            [price] => 123
        )
)

第二项丢失了,因为它的末尾没有分号,我不知道如何修复。

我现在意识到,这对字符串的数字部分有时会包含一个小数点,最后一个字符串对后面没有分号。任何提示都将不胜感激,因为我运气不好。

以下是考虑到我在最初的问题中遗漏的内容的更新字符串(对不起(:

12.30=one; two;45=three=four;600.00=five

您需要一个前瞻性断言;如果;后面跟一个数字或字符串的末尾,则前瞻性匹配:

$s = '12.30=one; two;45=three=four;600.00=five';
preg_match_all('/('d+(?:.'d+)?)=(.+?)(?=(;'d|$))/', $s, $matches);
print_r(array_combine($matches[1], $matches[2]));

输出:

Array
(
    [12.30] => one; two
    [45] => three=four
    [600.00] => five
)

我认为这就是您想要的正则表达式:

's*('d+)'s*=(.*?);(?='s*(?:'d|$))

诀窍是只考虑后面跟着一个数字的分号作为匹配的结束。这就是最后的展望。

您可以在www.debuggex.com.

上看到详细的可视化

您可以使用以下preg_match_all代码来捕获:

$str = '123=one; two;45=three=four;6=five;';
if (preg_match_all('~('d+)=(.+?);(?='d|$)~', $str, $arr))
   print_r($arr);

现场演示:http://ideone.com/MG3BaO

$str = '123=one; two;45=three=four;6=five;';
preg_match_all('/('d+)=([a-zA-z ;=]+)/', $str,$matches);
echo '<pre>';
print_r($matches);
echo '</pre>';

o/p:

Array
(
    [0] => Array
        (
            [0] => 123=one; two;
            [1] => 45=three=four;
            [2] => 6=five;
        )
    [1] => Array
        (
            [0] => 123
            [1] => 45
            [2] => 6
        )
    [2] => Array
        (
            [0] => one; two;
            [1] => three=four;
            [2] => five;
        )
)

那么y可以组合

echo '<pre>';
print_r(array_combine($matches[1],$matches[2]));
echo '</pre>';

o/p:

Array
(
    [123] => one; two;
    [45] => three=four;
    [6] => five;
)

尝试一下,但这段代码是用c#编写的,您可以将其更改为php

 string[] res = Regex.Split("123=one; two;45=three=four;6=five;", @";(?='d)");

--SJ