0

I'm trying to combine two separate regex queries into one default one in a small script I have.

The first query is

/\[(.*?)\]/g

Which matches shortcodes like this

[gallery]

The second query is

/\[([^\]]+)]([^\[]+)\[\/([^\]]+)]/g

Which matches shortcodes like this

[gallery]data[/gallery]

When I try to combine the queries, like this

/\[(.*?)\]|\[([^\]]+)]([^\[]+)\[\/([^\]]+)]/g

Everything is matched except the "data" inside an extended shortcode, like this.

[gallery]
[gallery][/gallery]

The result I am expecting / wanting to see is this

[gallery]
[gallery]data[/gallery]
2
  • 1
    Why not use two regex? Commented Aug 26, 2014 at 5:23
  • I have successfully used two regex's separately, but it would be tidier to combine them. Commented Aug 26, 2014 at 5:24

5 Answers 5

1

Just reverse the patterns. Because the order of matching is something like that the regex you gave first(ie, regex which was present just before to the OR | operator) would do the matching operation and next comes the second regex. You gave \[(.*?)\] as first regex so it matches also the strings that must be matched by the second regex. Reversing the order would force the regex engine to match strings like this [gallery]data[/gallery] on very first. After that the strings like this [gallery] would be matched.

\[([^\]]+)]([^\[]+)\[\/([^\]]+)]|\[(.*?)\]

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the fast contribution - problem solved. Thank you.
0
  \[([^\]]+)]([^\[]+)\[\/([^\]]+)]|\[(.*?)\]

Try this.The bigger first.

See Demo.

http://regex101.com/r/tK9sJ3/1

Comments

0

Try this:

\[(.*?)\](?:([^\[]+)\[\/([^\]]+)])?

Comments

0

just simple try:

/\[[^\]]+]([^\[]+\[\/[^\]]+])?/g

Regular expression visualization

Debuggex Demo

Comments

0

Using an optional non-capturing group, and a backreference to the first match:

/\[(.+?)\](?:([^\]]+)\[\/\1\])?/g

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.