0

I need to split a string to extract the parentheses and data in a string array using a Regex and keep the parentheses as well.

Extract from

1-2-3(0)(1)

To

(0)
(1)

I constructed this Regex, but can't make it work.

String phrase= "123(0)(1)"
String[] results = Regex.Split(phrase,"\\r+(?:\\(.*\\))");
  • `\r` matches a carriage return. Should be `\d`. –  May 17 '19 at 13:25
  • 2
    `Regex.Matches(input, @"\([^\)]+\)")`? – Sweeper May 17 '19 at 13:25
  • 7
    Possible duplicate of [Regular expression to extract text between square brackets](https://stackoverflow.com/questions/2403122/regular-expression-to-extract-text-between-square-brackets) Just substitute the square brackets for your parentheses. – sous2817 May 17 '19 at 13:25
  • https://stackoverflow.com/questions/2403122/regular-expression-to-extract-text-between-square-brackets – Chetan May 17 '19 at 13:25
  • `Regex.Matches(input, @"\((.*?)\)")` – Chetan May 17 '19 at 13:26

3 Answers3

1

You can use Regex.Matches method instead

        string phrase = "123(0)(1)";
        string[] results = Regex.Matches(phrase, @"\(.*?\)").Cast<Match>().Select(m => m.Value).ToArray();
Nicholas Mott
  • 102
  • 3
  • 13
0

You could try using substring method if those two in parenthesis will always be together.

phrase = phrase.Substring(phrase.FirstIndexOf("("));

Might have to put -1 after.

grendeld
  • 96
  • 1
  • 3
  • 9
0

You can extract the numbers in parentheses using (\(\d\)) pattern.

https://regex101.com/r/chjyLN/1

E.g.

var input = "1-2-3(0)(1)";
Regex pattern = new Regex(@"(\(\d\))");

var matches = pattern.Matches(input);

foreach (Match match in matches)
{
  foreach (Capture capture in match.Captures)
  {
      Console.WriteLine(capture.Value);
  }
}
Chris Pickford
  • 8,642
  • 5
  • 42
  • 73