Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match square bracket url tags

Tags:

regex

I'm trying to create a regular expression that will match square bracket url tags as follows:-

[url]some text[/url]

or

[url class="class"]some text[\url]

This is the pattern I have created

(\[url.*\])(.*?)(\[\\url\])

It works fine if there is only one tag however if I have two tags in a sentence as follows:

This is a sentence [url]blah[\url] this is another sentence[url]blah[\url]

It only has one match and grabs everything between the first opening and last closing [url] tag. I did some research and added the ? to stop it being greedy and grabbing everything but it doesn't work. I also tried using:

[^\[]* 

instead of

(.*?)

again it doesn't make a difference.

like image 439
user3168535 Avatar asked Jan 07 '14 10:01

user3168535


1 Answers

It's the first .* in your regex that's causing it not to work properly. Try this:

(\[url[^\]]*\])([^\[]*)(\[\\url\])

.* is being greedy and matches everything. If you check this group from your current regex, you'll actually see [url]blah[\url] this is another sentence[url] as the match, blah in the second group and [\url] in the third group.

like image 156
Jerry Avatar answered Nov 14 '22 05:11

Jerry