noobsaibot
noobsaibot

Reputation: 43

Regex C#: Split between two delimiters

Given I have a sample string below:

"parentstring1[childstring1.childstring2.childstring3].parentstring2[childstring4.childstring5]"

How can I split the string above to produce an array with the values below from '.' character and the '[' and ']' as delimiters

array[0] = "parentstring1[childstring1.childstring2.childstring3]"
array[1] = "parentstring2[childstring4.childstring5]"

Upvotes: 2

Views: 239

Answers (3)

yu_sha
yu_sha

Reputation: 4410

You can use Regex like this:

[^\[\.]+\[[^\]]*\]

This means: anything except . and [, followed by anything inside [] symbols.

MatchCollection matches = Regex.Matches(source, "[^\[\.]+\[[^\]]*\]")

demo

Upvotes: -1

Nader Hisham
Nader Hisham

Reputation: 5414

string text = "parentstring1[childstring1.childstring2.childstring3].parentstring2[childstring4.childstring5]";

string[] arr = Regex.Split(text, "(?<=\\]).");

foreach (var item in arr)
{
     Console.WriteLine(item);
}

Upvotes: 1

anubhava
anubhava

Reputation: 784878

You can split using this regex:

\.(?![^\[]*\])

RegEx Demo

This will split on DOTs only when it is not followed by 0 or more non-[ characters and a ], thus making sure to split on DOTs that are outside [...].

Upvotes: 1

Related Questions