Ben Marson
Ben Marson

Reputation: 5

Regex to extract text followed with parentheses (Multiple one in one String)

I want to extract text followed with parentheses of multiple one in one String.

Example:

text(text1) password(password1) in table(table_name) with some random text

So, i want extract each of them in table like this:

COL1          COL2
-------------------
text          text1
password      password1
table         table_name

So in table i mean just the possiblity to use them and call them when needed.

What i have tried:

This regex allow me only to extract the first parenthese but without "text" included and is not what i want:

"text(text1) password(password1) in table(table_name) with some random text".match(/\(([^)]+)\)/)[1]

return:

text1

I want "text" will be included in regex like explained in the example in the top of this post.

Thank's in advance.

Upvotes: 0

Views: 213

Answers (2)

The fourth bird
The fourth bird

Reputation: 163207

Your regex for the second part is ok but you should use exec instead of match and use the /g (Global) flag.

For the first capturing group your could match not a whitespace character \S

(\S+)\(([^)]+)\)

const regex = /(\S+)\(([^)]+)\)/g;
const str = `text(text1) password(password1) in table(table_name) with some random text`;
let m;

while ((m = regex.exec(str)) !== null) {
  if (m.index === regex.lastIndex) {
    regex.lastIndex++;
  }
  console.log(m[1], m[2]);
}

Upvotes: 1

Titus
Titus

Reputation: 22474

You can do something like this:

var str = "text(text1) password(password1) in table(table_name) with some random text";
var exp = new RegExp("([a-z]+)\\(([^)]+)\\)", "ig");

var groups = []
var matches
while(true){
  matches = exp.exec(str) 
  if (!matches) {
     break;
  }
  groups.push([matches[1], matches[2]])
}
console.log(groups)

You should probably change the regular expression, because now, the part before the parentheses can only contain letters.

Upvotes: 1

Related Questions