RegEX match everything outside square brackets

匆匆过客 提交于 2021-02-07 07:59:17

问题


I'm playing around with the WP editor and I'd like to create a RegEX pattern that matches everything outside the square brackets like this:

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

And replace with

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

I managed to match the square brackets content using

(\[(.*?)\])

How can I match everything else?

Thank you very much for your help!


回答1:


Can your text contain [?

If not you can use something in the spirit of

((?:\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

and replace it with

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

The idea is to catch the text that doesn't contain a [. When we stop, we know the next character will a [, so this is a tag, so we catch every consecutive [...] tags. Afterwards it's text again, so we reapply the pattern.

The "tag capture" before the text will only be used once, if the string starts with tags.

See demo here



来源:https://stackoverflow.com/questions/23152039/regex-match-everything-outside-square-brackets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!