Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: How to get all contents inside a tag #[SOME TEXT HERE]

Tags:

regex

I am working on a simple token replacement feature of our product. I have almost resolved all the issue but I missed one thing. A token must support attributes, and an attribute can also be a token. This is part of a bigger project. hope you can help.

The begining tag is "**#[**" and the ending tag is "**]**". Say, #[FirstName], #[LastName], #[Age, WhenZero="Undisclosed"].

Right now i am using this expression "\#\[[^\]]+\]". I have this working but it failed on this input:

blah blah text here...
**#[IsFreeShipping, WhenTrue="<img src='/images/fw_freeshipping.gif'/>
<a href='http://www.hellowebsite.net/freeshipping.aspx'>$[FreeShipping]</a>"]**
blah blah text here also...

It fails becauise it encouter the first ], it stops there. It returns:

*#[IsFreeShipping, WhenTrue="<img src='/images/fw_freeshipping.gif'/>
<a href='http://www.hellowebsite.net/freeshipping.aspx'>$[Product_FreeShipping]*

My desired result should be

*#[IsFreeShipping, WhenTrue="<img src='/images/fw_freeshipping.gif'/>
<a href='http://www.hellowebsite.net/freeshipping.aspx'>$[FreeShipping]</a>"]*

1 Answers

Your Regex matches exactly what your stated condition indicates : Start with an opening square bracket and match everything upto the first closing square bracket.

If you want to match nested square brackets, you need to specify exactly what is valid when nested. For instance, you could say that square brackets can be nested when enclosed within quotes.

like image 136
Cerebrus Avatar answered Dec 23 '25 01:12

Cerebrus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!