RegEX匹配方括号外的所有内容

时间:2014-04-18 10:17:39

标签: regex wordpress regex-negation

我正在玩WP编辑器,我想创建一个RegEX模式,匹配方括号外的所有内容,如下所示:

[foo]Some selected text here[/foo]More selected text here

并替换为

[foo][text_box text="Some selected text here"][/textbox][/foo]
[text_box text="More selected text here"][/textbox]

我设法使用

匹配方括号内容
(\[(.*?)\])

我怎样才能匹配其他所有内容?

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:2)

您的文字可以包含[吗?

如果没有,你可以按照

的精神使用某些东西
((?:\s*\[[^\]]+\])*)([^[]+)((?:\[[^\]]+\]\s*)*)

(                    # first capturing group
    (?:              # non capturing group
        \s*          # might be whitespaces
        \[           # opening [
        [^\]]+       # anything except a closing ]
        \]           # closing ]
    )*               # zero or more times
)
([^[]+)              # store in second capturing group any string that doesn't contain a [
((?:\[[^\]]+\]\s*)*) # catch tags in capture group 3

并将其替换为

$1[text_box text="$2"][/textbox]$3

想法是捕获不包含[的文本。当我们停止时,我们知道下一个字符将是[,因此这是一个标记,因此我们会捕获每个连续的[...]标记。之后又是文本,所以我们重新应用模式。

如果字符串以标签开头,则文本前的“标签捕获”将仅使用一次。

请参阅demo here