【问题标题】:regex - match brackets but exclude them from results正则表达式 - 匹配括号但从结果中排除它们
【发布时间】:2013-09-11 13:34:10
【问题描述】:

我有这个示例字符串

[can be anything here %+^-_][can be anything here %+^-_][can be anything here %+^-_][can be anything here %+^-_][can be anything here %+^-_][can be anything here %+^-_][can be anything here %+^-_][can be anything here %+^-_]

我的模式是(\[[^\]]+\])

结果我得到了这个

(
    [0] => Array
        (
            [0] => [can be anything here %+^-_]
            [1] => [can be anything here %+^-_]
            [2] => [can be anything here %+^-_]
            [3] => [can be anything here %+^-_]
            [4] => [can be anything here %+^-_]
            [5] => [can be anything here %+^-_]
            [6] => [can be anything here %+^-_]
            [7] => [can be anything here %+^-_]
        )

    [1] => Array
        (
            [0] => [can be anything here %+^-_]
            [1] => [can be anything here %+^-_]
            [2] => [can be anything here %+^-_]
            [3] => [can be anything here %+^-_]
            [4] => [can be anything here %+^-_]
            [5] => [can be anything here %+^-_]
            [6] => [can be anything here %+^-_]
            [7] => [can be anything here %+^-_]
        )

)

问题 1

为什么结果有两个数组?无论如何,这没什么大不了的,但我想知道。

问题 2

我怎样才能去掉每个数组值开头和结尾的括号,只使用正则表达式。像这样。

[0] => Array
            (
                [0] => can be anything here %+^-_
                [1] => can be anything here %+^-_
                [2] => can be anything here %+^-_
                [3] => can be anything here %+^-_
                [4] => can be anything here %+^-_
                [5] => can be anything here %+^-_
                [6] => can be anything here %+^-_
                [7] => can be anything here %+^-_
            )

【问题讨论】:

    标签: regex


    【解决方案1】:

    为什么结果有两个数组?

    因为将某些内容放在括号中 (()) 会为其分配一个组号,这就是组 1。第 0 组是您的整场比赛。请参阅this 了解更多信息。

    如何去掉每个数组值开头和结尾的括号?

    将您的正则表达式更改为:

    \[([^\]]+)\]
    

    对于上述情况,匹配的[]() 之外。这将使第 1 组成为您想要的。

    要使第 0 组成为您想要的,没有第 1 组,您必须使用look-around

    (?<=\[)[^\]]+(?=\])
    

    但这在很大程度上是不必要的。

    (?&lt;=\[) 是正向后视,检查前一个字符是否为 [,但不包括在匹配中。
    (?=\]) 是正向前瞻,检查下一个字符是 ],但不包括在匹配中。

    【讨论】:

      【解决方案2】:

      只需将大括号放在捕获组之外:

      \[([^\]]+)\]
      

      您有两个数组,因为一个是您的正则表达式的完全匹配,另一个是 () 捕获的。

      【讨论】:

        猜你喜欢
        • 2022-12-11
        • 2022-12-09
        • 2023-03-04
        • 2020-09-04
        • 2012-05-22
        • 2013-09-28
        • 1970-01-01
        • 2016-11-27
        • 2018-02-06
        相关资源
        最近更新 更多