简体   繁体   中英

C# Regex.Split (How to build)

I'm trying to split lines like those:

root.MediaClip.MaxGroups=10
root.MediaClip.M0.Name=Burglar_Alarm_Short
root.MediaClip.M0.Location=/etc/audioclips/Burglar_Alarm_Short_8bit_32kHz_mono_PCM-16bit-little.wav

But I can't figure out how to stop splitting after a "=".

Here the result the split should have:

root
MediaClip
MaxGroups=10

root
MediaClip
M0
Name=Burglar_Alarm_Short

root
MediaClip
M0
Location=/etc/audioclips/Burglar_Alarm_Short_8bit_32kHz_mono_PCM-16bit-little.wav

The problem are lines which end with a file extension. But after the "=" has arrived there is no need for an additional split.

You may use a regex based split to only split on dots that are followed with any chars other than = and then = or end of string, and not preceded with = :

(?<=^[^=]*)\.(?=[^=]*(?:=|$))

See the regex demo .

The (?<=^[^=]*) is a positive lookbehind requiring the dot to appear after a start of string ( ^ ) that is followed with 0+ chars other than = , and (?=[^=]*(?:=|$) positive lookahead also requires a = or end of string (see (?:=|$) non-capturing group) after 0+ chars other than = .

In C#:

var chunks = Regex.Split(str, @"(?<=^[^=]*)\.(?=[^=]*(?:=|$))");

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