问题
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