用于在花括号中分割分隔字符串的正则表达式模式

时间:2016-12-06 14:49:12

标签: c# arrays regex

我有以下字符串

{token1;token2;token3@somewhere.com;...;tokenn}

我需要一个Regex模式,它会在字符串数组中产生结果,例如

token1
token2
token3@somewhere.com
...
...
...
tokenn

如果可以使用相同的模式来确认字符串的格式,也会感谢一个建议,意味着字符串应该以花括号开头和结尾,并且锚点中至少存在2个值。

2 个答案:

答案 0 :(得分:0)

您可以使用带有命名重复捕获组的锚定正则表达式:

\A{(?<val>[^;]*)(?:;(?<val>[^;]*))+}\z

请参阅regex demo

  • \A - 字符串开头
  • { - {
  • (?<val>[^;]*) - 群组“val”捕获0+(由于*量词,如果值不能为空,则使用+)除;以外的字符
  • (?:;(?<val>[^;]*))+ - 序列中出现1次或多次(因此,{...}内至少需要2个值):
    • ; - 分号
    • (?<val>[^;]*) - 将“val”分组捕获除;
    • 以外的0 +字符
  • } - 文字}
  • \z - 字符串结束。

.NET regex将每个捕获都保存在CaptureCollection堆栈中,这就是为什么在找到匹配项后可以访问捕获到“num”组中的所有值。

C# demo

var s = "{token1;token2;token3;...;tokenn}";
var pat = @"\A{(?<val>[^;]*)(?:;(?<val>[^;]*))+}\z";
var caps = new List<string>();
var result = Regex.Match(s, pat);
if (result.Success)
{
    caps = result.Groups["val"].Captures.Cast<Capture>().Select(t=>t.Value).ToList();
}

答案 1 :(得分:0)

阅读它(与您的问题类似):How to keep the delimiters of Regex.Split?

对于RegEx测试,请使用此代码:http://www.regexlib.com/RETester.aspx?AspxAutoDetectCookieSupport=1

RegEx是一项资源密集型,运作缓慢的行动。

在您的情况下,最好使用Split类的string方法,例如:"token1;token2;token3;...;tokenn".Split(';');。它会返回一个你想要获得的字符串集合。

相关问题