正则表达式:先用分隔符然后再用另一个分隔符 [英] RegEx: Split string by separator and then by another

查看:49
本文介绍了正则表达式:先用分隔符然后再用另一个分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所需的行为存在问题.

假设有一个

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 $$.

推荐答案

此正则表达式<.code>(.*?)\ $ \ $(.*?)(?:\ ^ | $)将匹配名称值对,这是一个为证明这一点而使用的.要使用它,您可以使用以下代码:

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();
}

这篇关于正则表达式:先用分隔符然后再用另一个分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆