【问题标题】:Splitting a string in Regex c#在正则表达式 c# 中拆分字符串
【发布时间】:2021-12-14 19:55:52
【问题描述】:

我正在尝试通过以下方式在 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 }"

请帮我解决这个问题

【问题讨论】:

  • 您只是在寻找还是仅基于正则表达式的解决方案?
  • No.任何类型的解决方案

标签: c# regex string split


【解决方案1】:

你需要使用

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

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

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

(\s+[~-]\s+) 模式将任何一个或多个空格 + ~- + 一个或多个空格捕获到第 1 组。见regex demo

C# demo

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 }

【讨论】:

  • 如果我当时添加任何单词任何其他字符都不起作用。我必须再次改变模式。像 { Items.Test1 } ~ { Items.test2 } - { Items.Test3 } AND { items.test4 } 这个结果应该是 string[0]= { Items.Test1 } string[1]= ~ string[2]= { Items.test2 } string[3]= - string[4]= { Items.Test3 } string[5]= AND string[6]= { items.test4 }
  • @SumitManna 正确。有很多方法可以改进这个正则表达式。 1)(\s+(?:[~-]|AND)\s+)。或者,如果您需要确保匹配发生在 }{ 之间,2) (?&lt;=})(\s+(?:[~-]|AND)\s+)(?={)。另一种方法是只输出不带空格的字符/单词:3) (?&lt;=})\s+([~-]|AND)\s+(?={)。请选择你的命运...正则表达式:)
  • @SumitManna 我尝试添加 nоn-regex solution,但问题在于没有保留分隔符。我知道字符串拆分要快得多,但它会涉及更多更容易出错的代码。
【解决方案2】:

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

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

RegEx Demo

正则表达式详细信息:

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

代码:

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

【讨论】:

  • 如果我当时添加任何单词任何其他字符都不起作用。我必须再次改变模式。像 { Items.Test1 } ~ { Items.test2 } - { Items.Test3 } AND { items.test4 } 这个结果应该是 string[0]= { Items.Test1 } string[1]= ~ string[2]= { Items.test2 } string[3]= - string[4]= { Items.Test3 } string[5]= AND string[6]= { items.test4 }
  • 在这种情况下,只需交替添加AND,例如:pattern = @"[~-]|AND|{[^}]*}"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-30
相关资源
最近更新 更多