Using regular expressions to find the text between two delimiters

I have a string like this:  “This is a [abcd] string”.  I want to find the text between the square brackets.  Looks like a job for regular expressions!

This regular expression works:  “\[.*\]“.  Very straightforward (for a regular expression) – I like it!

Then I saw this regular expression in some question and answer forum:  “\[([^\}]+)\]“.  It works, but seems unclear.  Is that something clever or a bad piece of advice?  If I understand it correctly, it is saying:  Find the text contained in the square brackets UNLESS it contains a “}” character.  Huh?  I’m chalking it down to bad advice.

One caveat is that if I have the string “This is my [abcd][efgh] string”, I get the string within the outer brackets, that is: “[abcd][efgh]”, when I really would want “[abcd]”.  I have a feeling that this is a problem I will have to solve … but not today!


Post a Comment

Required fields are marked *

%d bloggers like this: