簡體   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