可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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