IHTESHAM
IHTESHAM

Reputation: 11

Splitting string by parenthesis

I have a string like abcdef(1)ghijkllskjdflkjsdfsdf(2)aslkdjfjgls(3)jgjgjkdkgkdll

I want to split it into n number of lines depending on occurences of (n) in the string.

For example in above string, following is acheived :

lines [0] = abcdef
lines [1] = ghijkllskjdflkjsdfsdf
lines [2] = aslkdjfjgls
lines [3] = jgjgjkdkgkdll.

What i am trying is :

StringBuilder sb = new StringBuilder();

var pattern = @"((.*))"; 

string[] lines = Regex.Split(text,pattern);

foreach (string line in lines)
{
    sb.AppendLine(line);
}

string FinalText = sb.ToString();

Can anyone help with C# regular expressions or string split function ?

Thank you.

Upvotes: 1

Views: 1279

Answers (2)

Paul
Paul

Reputation: 4259

The follow regex will match your numbered brackets:

\(\d+\)

Your usage of Regex.Split is correct, so I do not know why you need help with that!?

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292555

string pattern = @"\(\d+\)";
string[] lines = Regex.Split(text,pattern);
string finalText = String.Join(Environment.NewLine, lines);

Upvotes: 4

Related Questions