繁体   English   中英

在 Regex c# 中拆分字符串

[英]Splitting a string in Regex c#

我正在尝试按以下方式在 C# 中拆分字符串:

输入字符串的格式为

{ Items.Test1 } ~ { Items.test2 } - { Items.Test3 }

我正在尝试将其拆分为表单中的字符串数组

string[0]= "{ Items.Test1 }"
string[1]= " ~ "
string[2]=  "{ Items.test2 }"
string[3]= " - "
string[4]= "{ Items.Test3 }"

我试图以这样的方式做到这一点

string[] result1 = Regex.Matches(par.Text.Trim(), @"\{(.*?)\}").Cast<Match>().Select(m => m.Value).ToArray();

它工作不正常。 显示以下结果。

string[0]="{ Items.Test1 }"
string[1]="{ Items.test2 }"
string[2]="{ Items.Test3 }"

请帮我解决这个问题

你需要使用

Regex.Split(par.Text.Trim(), @"(\s+[~-]\s+)")

当使用包含捕获组的正则表达式进行拆分时,捕获的文本也会作为结果数组的一部分输出。 请参阅Regex.Split文档

如果在Regex.Split表达式中使用捕获括号,则任何捕获的文本都包含在结果字符串数组中。

(\\s+[~-]\\s+)模式将任何一个或多个空格 + ~- + 一个或多个空格捕获到组 1 中。 请参阅正则表达式演示

在此处输入图片说明

请参阅C# 演示

var pattern = @"(\s+[~-]\s+)";
var text = "{ Items.Test1 } ~ { Items.test2 } - { Items.Test3 }";
var result = Regex.Split(text, pattern);
// To also remove any empty items if necessary:
//var result = Regex.Split(text, pattern).Where(x => !String.IsNullOrWhiteSpace(x)).ToList();
foreach (var s in result)
    Console.WriteLine(s);

输出:

{ Items.Test1 }
 ~ 
{ Items.test2 }
 - 
{ Items.Test3 }

您可以使用此正则表达式进行匹配:

[~-]|{[^}]*}

正则表达式演示

正则表达式详情:

  • [~-] : 匹配一个~-
  • | : 或者
  • {[^}]*} : 匹配一个{...}子串

代码:

string pattern = @"[~-]|{[^}]*}";
string sentence = "{ Items.Test1 } ~ { Items.test2 } - { Items.Test3 }";
  
foreach (Match m in Regex.Matches(sentence, pattern))
   Console.WriteLine("Match '{0}' at position {1}", m.Value, m.Index);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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