简体   繁体   English

正则表达式以使用javascript匹配一对矩形括号

[英]RegEx to match pair of Rectangular Brackets using javascript

Can someone help me with a Javascript regular expression? 有人可以帮我编写Javascript正则表达式吗? I need to match pairs of brackets. 我需要匹配成对的括号。 For example, it should match "[abc123]", "[123abc]" in the following string: 例如,它应与以下字符串中的“ [abc123]”,“ [123abc]”匹配:

"this is a test [abc123]], another test [[123abc]. This is an left alone closing" “这是一个测试[abc123]],另一个测试[[123abc]。这是一个单独的结局”

Thanks in advance. 提前致谢。

If you don't require nested brackets, 如果您不需要嵌套的方括号,

// theString = "this is a test [abc123]], another test [[123abc]. 
// This is an left alone closing";
return theString.match(/\[[^\[\]]*\]/g);
// returns ["[abc123]", "[123abc]"]

to extract the contents, see the following example: 要提取内容,请参见以下示例:

var rx = /\[([^\[\]]*)\]/g;
var m, a = [];
while((m = rx.exec(theString)))      
  a.push(m[1]);
return a;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM