Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract all strings between brackets using c#? [duplicate]

Tags:

c#

regex

split

If I have a string such as:

"You id is (1) and your number is (0000000000)"

What is the best way to extract these these strings into a list of strings. The numbers between the brackets can increase in digits thus searching for the strings between the brackets is a better technique.

I can use the code below to extract the first string between brackets.

var myString = "You id is (1) and your number is (0000000000)";
var firstNumberBetweenBrackets = myString.Split('(', ')')[1]; // would return 1
like image 513
eVolve Avatar asked Feb 25 '18 11:02

eVolve


People also ask

How do I extract text that lies between parentheses?

The simplest way to extract the string between two parentheses is to use slicing and string. find() .

What do parentheses () and brackets [] In differ?

Parentheses and brackets are punctuation marks used to set apart certain words and sentences. Parentheses, ( ), are used to add extra information in text, while brackets, [ ], are used mainly in quotations to add extra information that wasn't in the original quote.


2 Answers

Here is a LINQ solution:

var result = myString.Split().Where(x => x.StartsWith("(") && x.EndsWith(")")).ToList();

Values stored in result:

result[0] = (1)
result[1] = (0000000000)

And if you want only the numbers without the brackets use:

var result = myString.Split().Where(x => x.StartsWith("(") && x.EndsWith(")"))
                     .Select(x=>x.Replace("(", string.Empty).Replace(")", string.Empty))
                     .ToList();

Values stored in result:

result[0] = 1
result[1] = 0000000000
like image 98
Slaven Tojic Avatar answered Sep 30 '22 01:09

Slaven Tojic


You can use Regex for this (https://regex101.com/r/T4Sdik/1):

Regex regex = new Regex(@"\(([^()]+)\)*");

foreach (Match match in regex.Matches("You id is (1) and your number is (0000000000)")
{
    Console.WriteLine(match.Value);
}

This will print:

1
0000000000
like image 25
Haytam Avatar answered Sep 29 '22 23:09

Haytam