正则表达式匹配括号 [英] Regular expression to match brackets

查看:159
本文介绍了正则表达式匹配括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于模板引擎,我使用正则表达式来标识字符串中括号内的内容。例如,正则表达式需要匹配{key}或< tag>或[元素]。

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}]

正则表达式将匹配 [{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 >

推荐答案

最好的方法,特别是如果不同的括号可以有不同的含义,分为3个正则表达式:

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.

这篇关于正则表达式匹配括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆