0

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.

  • `let reg = /(\w+)\(([^)]+)\)/g, result = [], currentMatch; while((currentMatch = reg.exec(txt)) !== null) { result.push({ name: currentMatch[1], param: currentMatch[2] }); }` – ASDFGerte Aug 11 '18 at 18:25
  • @ASDFGerte thank you ! it was the best answer yes. – Ben Marson Aug 11 '18 at 18:41

2 Answers2

1

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.

Titus
  • 22,031
  • 1
  • 23
  • 33
1

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]);
}
The fourth bird
  • 154,723
  • 16
  • 55
  • 70