简体   繁体   中英

RegEx: Split string by separator and then by another

There is a problem with needed behavior.

Assume there is a

sourceString = @"name1$$value1^name2$$value2^name3$$value3";

maybe more long string...

I'd like to first split by ^ separator and then by another $$ to create dictionary based on this name-value pairs.

This string is stored in file so may be too long, any split operations may take too much time. I hope there is a regex with match by ^ and internal groupmatch by $$ .

This regex (.*?)\\$\\$(.*?)(?:\\^|$) will match the name value pairs, and here is a Rubular to prove it . And to use it you can use the following code:

var input = "name1$$value1^name2$$value2^name3$$value3";
var pattern = @"(.*?)\$\$(.*?)(?:\^|$)";
var hash = new Dictionary<string, string>();
var match = Regex.Match(input, pattern);

while (match.Success)
{
    hash.Add(match.Groups[1].Value, match.Groups[2].Value);
    match = match.NextMatch();
}

Why not use:

sourceString.Split(new char[] {'^'}, StringSplitOptions.RemoveEmptyEntries)

Then you can do the same for $$

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