-1

I need to get multiple texts from more than one set of parentheses, and if there is no more than one set then I need to get text from only that single set of parentheses.

1) Example :

My sentence is :
                  A Cef (1000mg) (Sterlie Ceftriaxone) Price List.

Now, I need to get the output like this :

  Output :
                 1000mg Sterlie Ceftriaxone

2) Also if I have only single set like this : Aamin A (Atenolol) Price List.

Then my output should be : Atenolol

I am using this javascript code :

function myFunction() {
    var str = "A Cef (1000mg) (Sterlie Ceftriaxone) Price List."; 
    var res = str.match(/\((.*))\)/);
    document.getElementById("demo").innerHTML = res[1];
}

It is perfectly working for the 2nd case but when I am using it for the 1st one it giving me this output.

         Output :1000mg) (Sterlie Ceftriaxone 
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
Coder
  • 13
  • 7
  • I think you have too many brakets on the right hand side. Try this `var res = str.match(/\((.*)\)/);` – Ari May 01 '17 at 17:53
  • i have used same expression as u suggested. Its not working for 1st one. – Coder May 01 '17 at 17:57

3 Answers3

2

Use a non-greedy expression /\((.+?)\)/gm. See https://regex101.com/r/OKvbXy/1

function myFunction(text) {
    var res = text.match(/\((.+?)\)/g);
    var cleanedUp = res.join(' ').replace(/[()]/g,''); // remove () and join matches
    console.log( cleanedUp );
}

myFunction("A Cef (1000mg) (Sterlie Ceftriaxone) Price List.");
myFunction("Aamin A (Atenolol) Price List.");

Btw, your code has nothing to do with jQuery (you are not even using it in your code)

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
1

It's because * is greedy. You also want to do a global match to get all results.

Try this instead -

str.match(/\(([^\)]+)\)/g)

Community
  • 1
  • 1
alpeware
  • 472
  • 2
  • 8
0

I belive the issue is that by using the .* (wildcard) you are capturing the brackets and the spaces.

If you use var res = str.match(/\(([0-9a-zA-Z]+)\)/); instead, it will work to capture the first group, as it will not match the brackets or whitespace in your example.

Ari
  • 745
  • 1
  • 7
  • 23