0

I try to split a string in C#.

Example1: "( Nr:1234 ) and ( Name:Test )"

Example2: "( Nr:1234 ) or ( Name:Test ) or ( Nr:456 ) or ( Name:A* )"

I need the strings inside of the brackets like f.e. "Nr:1234" or "Name:Test" into an array or a list of strings. There is always a space after the opening and before the closing bracket and before/after or respectively and.

I have tried this:

Regex r = new Regex(@"\((.*?)\)");
MatchCollection matches = r.Matches(sSearchString);
var list = matches.Cast<Match>().Select(match => match.Value).ToList();

But sometimes it is possible that the name also contains brackets, f.e. like this:

"( Name:This is a test (number one) ) or ( Nr:234 )"

Mazunte
  • 1
  • 1
  • Please also check [this thread](https://stackoverflow.com/questions/378415/how-do-i-extract-text-that-lies-between-parentheses-round-brackets) first. – Wiktor Stribiżew Sep 29 '20 at 14:37
  • Have a look at c# [`string.Split()`](https://learn.microsoft.com/en-us/dotnet/api/system.string.split?view=netcore-3.1) method if you don't want to look into regex. This method can be used to split on multiple delimiters. After that you only have to get rid of the parentheses. This could be done by using `string.Replace()` for example. – croxy Sep 29 '20 at 14:47
  • ```string pattern = @"\( ([^\)]+) \)"; MatchCollection matchList = Regex.Matches(input, pattern); var list = matchList.Cast().Select(match => match.Groups[1]).ToList();``` – Platypus Sep 29 '20 at 15:09
  • @Platypus Thx, but this doesn't work for a string like: "( Name:This is a test (number one) ) or ( Nr:234 )" – Mazunte Sep 29 '20 at 15:36
  • That works for me: https://stackoverflow.com/questions/38713119/c-sharp-regex-for-matching-sepcific-text-inside-nested-parentheses – Mazunte Sep 29 '20 at 16:05
  • `var list = Regex.Matches(input, @"\((?(?>[^()]+|(?)\(|(?<-o>)\))*\)(?(o)(?!)))").Cast().Select(match => match.Groups["res"].Value).ToList();` – Wiktor Stribiżew Sep 29 '20 at 20:04
  • @WiktorStribiżew In this case all matched strings contains only the right parenthesis – Mazunte Sep 30 '20 at 06:45
  • Sure, I did not check it, so it must be `\((?(?>[^()]+|(?)\(|(?<-o>)\))*)\)(?(o)(?!))` – Wiktor Stribiżew Sep 30 '20 at 07:25
  • @Mazunte so try that `\( ([^]+) \)` – Platypus Oct 01 '20 at 11:56

0 Answers0