Regular expression to match square bracket URL tags

I am trying to create a regular expression that will match the square brackets URL tags as follows: -

[url]some text[/url] 

or

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

This is the template that I created.

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

It works fine if there is only one tag, if I have two tags in the sentence:

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

It has only one match and captures everything between the first opening and the last closing [url] tag. I did some research and added ? to stop his greed and seizure of everything, but he does not work. I also tried using:

 [^\[]* 

instead

 (.*?) 

again it doesn't matter.

+6
source share
4 answers

This is the first .* In your regex that makes it work incorrectly. Try the following:

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

.* greedily and fits everyone. If you check this group from the current regular expression, you will actually see [url]blah[\url] this is another sentence[url] as a match, blah in the second group and [\url] in the third group.

+1
source

.* can be a little dangerous if you know in advance that you have text / numbers that you use [a-zA-Z0-9] and avoid this problem.

Something like: \[url\][a-zA-Z0-9]+\[\\url\]

0
source

To be more specific, you can give:

 (\[url( .+[=].+\])*)[z-zA-Z0-9 ](\[\url\]) 
0
source

For url tags only:

 (?:\[url])([^\[]+)\[[\/\\]url] 

Live demo

To remove all tags:

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

Live demo

0
source

All Articles