bsiddiqui
bsiddiqui

Reputation: 1926

Regex match within parens

There are a lot of questions on SO re: matching within a brackets, parens, etc but I'm wondering how to match within a character (parens) while ignoring that character

"Key (email)=(basil@gmail.com) already exists".match(/\(([^)]+)\)/g)
// => ["(email)", "(basil@gmail.com)"]

I believe this is because JS doesn't support [^)]. Given that, how would you recommend extracting the values within the parens.

I'd prefer something less hacky than having to call .replace('(', '').replace(')', '') on the values

I'd like the return value to be ["email", "basil@gmail.com"]

Upvotes: 3

Views: 297

Answers (4)

Roko C. Buljan
Roko C. Buljan

Reputation: 206565

Extract text between braces () not returning braces

using this two banally simple examples:

Using .match() to extract and construct the Array

var arr = "Key (email)=(basil@gmail.com) already exists".match(/(?<=\()[^)]+(?=\))/g);

console.log( arr );

https://regex101.com/r/gjDhSC/1
MDN - String.prototype.match()


Using .replace() to extract values and push to Array

var arr=[];

"Key (email)=(basil@gmail.com) already exists"
    .replace(/\(([^)]+)\)/g, (p1, p2) => arr.push(p2) );

console.log( arr );

https://regex101.com/r/gjDhSC/2
MDN - String.replace()

Upvotes: 4

cpugourou
cpugourou

Reputation: 781

var str = "Key (email)=(basil@gmail.com) already exists";
var matches = [];
str.replace(/\((.*?)\)/g, function(g0,g1){matches.push(g1);})

Upvotes: 0

wally
wally

Reputation: 3592

See here: How do you access the matched groups in a JavaScript regular expression?

Combine with @pherris' comment:

var str = "Key (email)=(basil@gmail.com) already exists";
var rx = /\((.+?)\)/ig;
match = rx.exec(str);
alert(match[1]);
while (match !== null) {
   match = rx.exec(str);
   alert(match[1]);
}

JSfiddle: https://jsfiddle.net/60p9zg89/ (will generate popups)


This executes the regex multiple times, returning the captured string (in the brackets).

Pushing an alert to the browser isn't very useful, you specified returning an array - so:

function rxGroups(rx, str) {
   var matches = new Array();
   match = rx.exec(str);
   while (match != null) {
      matches.push(match[1]);
      match = rx.exec(str);
   }
   return matches;
}

var x = rxGroups(
   /\((.+?)\)/ig,
   "Key (email)=(basil@gmail.com) already exists"
);

alert(x.join('\n'));

https://jsfiddle.net/60p9zg89/1/

Upvotes: 2

Kristian Oye
Kristian Oye

Reputation: 1202

You may be wanting the result of the first capture group. After your match you can get the first group:

(function(s, x) {
 return s.match(x)
    .map(function(m) {
      var f = m.match(x);
      return RegExp.$1;
    });
})('Key (email)=(basil@gmail.com) already exists', /\(([^()]+)\)/g)

Result = ["email", "basil@gmail.com"]

Upvotes: 0

Related Questions