tags:

views:

50

answers:

3

Hi,

I want a regex pattern to find all the words of this format [xyzblab23la].

For example if the text has something like the following,

Lorem Ipsum dolor[32a] ameit[34]

I should be able to find the [32a] and [34]. Please tell me what is the regex for this pattern?

+6  A: 

You can use the following regex globally to find all the matches:

\[.*?\]

or

\[[^\]]*\]

Explanation:

  • \[ : [ is a meta char for the start of the char class, so to match a literal [ we need to escape it.
  • .*? : match everything in a non-greedy way.
  • \] : to match a literal ]
  • [^\]] : a char class that matches any char other than ]
  • [^\]]* : zero or more char of the above type.
codaddict
Why have you stressed on the word 'globally'. Does that mean anything in regex world (i'm new to regex patterns)
Bragboy
Since you want to find *all* such patterns, we need to match the regex globally. By default (at least in Perl and in PHP-using preg_match) the matching process stops once it finds one match. In Perl we use the *g* option to the regex and in PHP we use the preg_match_all function to do the matching globally.
codaddict
+5  A: 

Try this regular expression:

\[[^[\]]+]

A short explanation:

  • \[ matches a plain [
  • [^[\]]+ matches one or more arbitrary characters except [ and ]
  • ] matches a plain ]
Gumbo
+1  A: 
/(\[[a-z0-9]+\])/i/
Rob