Hello All,
I want to break the string by using the Regular Expression:
String:"ALLRAD + !(812_ENGLAND, US)"
Output:"(ALLRAD + !(812_ENGLAND))"
"(ALLRAD + !(US))"
Thanks in Advance
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
VulpesPosted Apr 15, 2014, 11:26 AM
Try the following which I've tried to generalize so that it can deal with more than 2 strings in the comma separated list:
using System;
using System.Text.RegularExpressions;
class Test
{
static void Main()
{
string str = "ALLRAD + !(812_ENGLAND, US)";
string regExp = @"^(\w+\s*\+\s*(!)?)\((\w+(,\s*\w+)*)\)$";
Match m = Regex.Match(str, regExp);
string[] split = Regex.Split(m.Groups[3].Value, @",\s*");
string[] output = new string[split.Length];
for(int i = 0; i < split.Length; i++)
{
output[i] = String.Format("({0}({1}))", m.Groups[1], split[i]);
Console.WriteLine(output[i]);
}
Console.ReadKey();
}
}
The output is:
(ALLRAD + !(812_ENGLAND))
(ALLRAD + !(US))
If the original string had been:
"ALLRAD + !(812_ENGLAND, US,FRANCE,PORTUGAL)"
the output would have been:
(ALLRAD + !(812_ENGLAND))
(ALLRAD + !(US))
(ALLRAD + !(FRANCE))
(ALLRAD + !(PORTUGAL))