0

我有这个示例字符串

[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 %+^-_
            )
4

2 回答 2

1

为什么结果有两个数组?

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

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

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

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

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

要使第 0 组成为您想要的,没有第 1 组,您必须使用环视

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

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

(?<=\[)是积极的后视,检查前一个字符是 a [,但不包括在匹配中。
(?=\])是积极的前瞻,检查下一个字符是 a ],但不包括在匹配中。

于 2013-09-11T13:45:10.307 回答
0

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

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

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

于 2013-09-11T13:42:37.117 回答