正则表达式匹配 JavaScript 的圆括号和方括号 [英] Regular Expression to match parentheses and brackets for JavaScript

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

问题描述

我有这个匹配括号内文本的正则表达式:

I have this regex that matches text inside parentheses:

/\([^\)]*?\)/g

我希望能够同时匹配圆括号和方括号,以便它检测字符串中的圆括号和方括号,以便我可以为它着色.

I want to be able to match both parentheses and brackets so it will detect both parentheses and brackets in a string so I can color it.

这应该是字符串:

The (quick) brown [fox]

我想给 (quick)[fox] 着色,所以我需要正则表达式来匹配括号和括号.

I want to color (quick) and [fox] so I need the regex to match both parentheses and brackets.

谢谢.

推荐答案

这应该有效:

/\([^)]*\)|\[[^\]]*\]/g;

在下面试试:

var str = "The (quick) brown [fox]";

var re = /\([^)]*\)|\[[^\]]*\]/g;

str.match(re).forEach(function(m) {
  document.body.insertAdjacentHTML('beforeend', m + '<br>');
});

Regex101

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

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