代码之家  ›  专栏  ›  技术社区  ›  Claudio

在方括号内的每个字符上拆分

  •  2
  • Claudio  · 技术社区  · 7 年前

    我的regex有问题,我有以下字符串

    [date|Y-m-d]
    

    这是一个从文本中提取的令牌,我需要提取“日期”和“Y-M-D”,但我还没有通过以下regex实现我的目标,有人能帮我吗?

    (?:\[)([^\|]+)(?:\])
    

    代币可以是:

    [date|Y-m-d] \\ should extract 'date' and 'Y-m-d'
    [date|Y-m-d|today] \\ should extract 'date', 'Y-m-d' and 'today'
    
    3 回复  |  直到 7 年前
        1
  •  -1
  •   Ωmega    7 年前

    使用regex模式

    (?<=^\[|\|)[^|\[\]]*(?=\||\]$)
    

    here here

        2
  •  3
  •   Sambhaji Katrajkar    7 年前

    $str = explode(':', ltrim( rtrim($str, ']'), '['));
    print_r( $str );
    

    Array
    (
        [0] => date
        [1] => Y-m-d
    )
    
        3
  •  2
  •   Wiktor Stribiżew    7 年前

    括号内的子字符串,您希望提取它们。

    $str = '[date|Y-m-d] [date|Y-m-d|today]';
    preg_match_all('/\[([^][]+)]/', $str, $matches);
    $res = [];
    foreach ($matches[1] as $m) {
        array_push($res,explode("|", $m));
    }
    print_r($res);
    

    查看 PHP demo

    PHP demo

    $str = 'A single match example [date|Y-m-d|today] here.';
    if (preg_match('/\[([^][]+)]/', $str, $matches)) {
        print_r(explode("|", $matches[1]));
    }
    

    细节

    • '/\[([^][]+)]/' [ ]
    • |

    如果你的字符串等于 [...|...|...|etc.] Shivrudra's approach 或者非常简单的 preg_match_all

    $str = '[date|Y-m-d]';
    preg_match_all('/[^][|]+/', $str, $matches);
    print_r($matches[0]);
    

    参见 another PHP demo

    这个 [^][|]+ [ the regex demo .