简体   繁体   English

在 Regex c# 中拆分字符串

[英]Splitting a string in Regex c#

I am trying to split a string in C# the following way:我正在尝试按以下方式在 C# 中拆分字符串:

The Input string is in the form输入字符串的格式为

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

And I am trying to split it into an array of strings in the form我正在尝试将其拆分为表单中的字符串数组

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

I was trying to do it in a way such as this我试图以这样的方式做到这一点

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

It is not working correctly.它工作不正常。 Showing below results.显示以下结果。

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

pls help me on this请帮我解决这个问题

You need to use你需要使用

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

When splitting with a regex containing a capturing group, the captured texts are also output as part of the resulting array.当使用包含捕获组的正则表达式进行拆分时,捕获的文本也会作为结果数组的一部分输出。 See the Regex.Split documentation :请参阅Regex.Split文档

If capturing parentheses are used in a Regex.Split expression, any captured text is included in the resulting string array.如果在Regex.Split表达式中使用捕获括号,则任何捕获的文本都包含在结果字符串数组中。

The (\\s+[~-]\\s+) pattern captures into Group 1 any one or more whitespaces + ~ or - + one or more whitespaces. (\\s+[~-]\\s+)模式将任何一个或多个空格 + ~- + 一个或多个空格捕获到组 1 中。 See the regex demo :请参阅正则表达式演示

在此处输入图片说明

See the C# demo :请参阅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);

Output:输出:

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

You can use this regex for matching:您可以使用此正则表达式进行匹配:

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

RegEx Demo 正则表达式演示

RegEx Details:正则表达式详情:

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

Code:代码:

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