Regular expression to match brackets

后端 未结 4 1497
清酒与你
清酒与你 2021-01-04 11:37

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 or [element

4条回答
  •  感动是毒
    2021-01-04 12:17

    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.

提交回复
热议问题