Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match brackets

For a templating engine, I am using regular expressions to identify content under brackets in a string. For example the regex needs to match {key} or <tag> or [element].

Currently my regular expression looks like this:

var rx=/([\[\{<])([\s\S]+?)([\]\}>])]/;

The issue is that such a regular expression doesn't force brackets to match. For example in the following string:

[{lastName},{firstName}]

the regular expression will match [{lastName}

Is there a way to define matching brackets? Saying for example that if the opening bracket is a [ then the closing bracket must be a ], not a } or a >

like image 824
Christophe Avatar asked Aug 10 '12 18:08

Christophe


People also ask

How do you use brackets 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 does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

How do you match a square bracket in regex?

You can omit the first backslash. [[\]] will match either bracket. In some regex dialects (e.g. grep) you can omit the backslash before the ] if you place it immediately after the [ (because an empty character class would never be useful): [][] .

How do you match curly braces with regular expressions?

To match literal curly braces, you have to escape them with \ . However, Apex Code uses \ as an escape, too, so you have to "escape the escape". You'll need to do this almost every time you want to use any sort of special characters in your regexp literally, which will happen more frequently than not.


1 Answers

The best way to do this, especially if different brackets can have different meanings, is to split into 3 regular expressions:

var rx1 = /\[([^\]]+)]/;
var rx2 = /\(([^)]+)\)/;
var rx3 = /{([^}]+)}/;

These will match any text surrounded by [], (), and {} respectively, with the text inside in the first matched group.

like image 90
murgatroid99 Avatar answered Sep 17 '22 12:09

murgatroid99