简体   繁体   中英

Regex.Split help in C#

I have this string:

A,B,C[D,E,F[G,H,J[I]],K,L[M,N] 

And with Regex.Split() i need a result divided like this:

A,B
C[D,E]
F[G,H]
J[I]
K
L[M,N]

I'm not sure if you can do this purely with a regular expression (and if it is possible then I suspect that the required regex would be hellishly complex).

Here's one alternative, although it might be better to skip the regex entirely and parse everything manually:

string yourString = "A,B,C[D,E,F[G,H,J[I]],K,L[M,N]";

var parts = Regex.Split(yourString, @",(?=[^,\[]+\[)|\]+,?")
                 .Where(s => s.Length > 0)
                 .Select(s => s.Contains("[") ? s + "]" : s);

Try this:

Regex re = new Regex(@"((?:\w+)\[(?:(?:\w+\b,?)(?!\[))+)");

var result = re.Split(str.Replace(" ", ""))
               .Select(s => s.TrimEnd(',', '[').TrimStart(']', ','))
               .Where(s => !string.IsNullOrEmpty(s));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM