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 >
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.
$ means "Match the end of the string" (the position after the last character in the string).
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): [][] .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With