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
The simplest way to extract the string between two parentheses is to use slicing and string. find() .
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With