How to get the contents between 2 parenthesis using Regex?

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

I have a string that looks like this:

(Boxing Bag@bag.jpg@To punch and kick)(Wallet@wallet.jpg@To keep money in)

How can I extract the contents within the parenthesis so I get 2 strings:

Boxing Bag@bag.jpg@To punch and kick Wallet@wallet.jpg@To keep money in

What would be the regex for this using JavaScript?

回答1:

Using suat's regex, and since you want to do global matching with groups, you need to use a loop to get all the matches:

var str = '(Boxing Bag@bag.jpg@To punch and kick)(Wallet@wallet.jpg@To keep money in)'; var regex = new RegExp('\\((.*?)\\)', 'g'); var match, matches = []; while(match = regex.exec(str))     matches.push(match[1]); alert(matches); // ["Boxing Bag@bag.jpg@To punch and kick", "Wallet@wallet.jpg@To keep money in"]


回答2:

This regex /[^()]+/g matches all series of characters which are not ( or ):

var s = '(Boxing Bag@bag.jpg@To punch and kick)'+ // I broke this for readability         '(Wallet@wallet.jpg@To keep money in)'.match(/[^()]+/g) console.log(s) // ["Boxing Bag@bag.jpg@To punch and kick",                //  "Wallet@wallet.jpg@To keep money in"]


回答3:

I created a little javascript library called balanced to help with tasks like this. As mentioned by @Paulpro the solution breaks if you have content in between the parenthesis, which is what balanced is good at.

var source = '(Boxing Bag@bag.jpg@To punch and kick)Random Text(Wallet@wallet.jpg@To keep money in)';  var matches = balanced.matches({source: source, open: '(', close: ')'}).map(function (match) {     return source.substr(match.index + match.head.length, match.length - match.head.length - match.tail.length); });  // ["Boxing Bag@bag.jpg@To punch and kick", "Wallet@wallet.jpg@To keep money in"]

heres a JSFiddle example



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!