Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to extract text between square brackets

Tags:

regex

Simple regex question. I have a string on the following format:

this is a [sample] string with [some] special words. [another one] 

What is the regular expression to extract the words within the square brackets, ie.

sample some another one 

Note: In my use case, brackets cannot be nested.

like image 705
ObiWanKenobi Avatar asked Mar 08 '10 17:03

ObiWanKenobi


People also ask

How do you use square brackets in regex?

Use square brackets ( [] ) to create a matching list that will match on any one of the characters in the list. Virtually all regular expression metacharacters lose their special meaning and are treated as regular characters when used within square brackets.

What do the [] brackets mean in regular expressions?

By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together. This allows you to apply a quantifier to the entire group or to restrict alternation to part of the regex. Only parentheses can be used for grouping.

What's the difference between () and [] in regular expression?

[] denotes a character class. () denotes a capturing group. (a-z0-9) -- Explicit capture of a-z0-9 . No ranges.


1 Answers

You can use the following regex globally:

\[(.*?)\] 

Explanation:

  • \[ : [ is a meta char and needs to be escaped if you want to match it literally.
  • (.*?) : match everything in a non-greedy way and capture it.
  • \] : ] is a meta char and needs to be escaped if you want to match it literally.
like image 104
codaddict Avatar answered Sep 21 '22 06:09

codaddict