[英]c# Regex Split Binary String
我正在嘗試以特定方式拆分一串二進制數字
假設這是我的字符串100011001110010101110
我想在1之前的每個0處拆分字符串
所以拆分后上面的字符串變成
1000 1100 11100 10 10 1110
我使用了 Regex 模式/(1+0+)/g
來正確分割字符串,但它遺漏了一些組。 這是c#代碼
Regex.Split(stringToSplit, @"(1+0+)");
請問我錯了什么。
編輯:我沒有提到我確定1總是先於0
提前致謝。
您可以嘗試向前看和向后看,即在零長度文本上溢出,拆分后面為0
,前面為1
代碼:
string source = "100011001110010101110";
var result = Regex.Split(source, "(?<=0)(?=1)");
// Let's have a look
Console.Write(string.Join(Environment.NewLine, result));
結果:
1000
1100
11100
10
10
1110
編輯:模式(?<=0)(?=1)
解釋:
(?<=0) - 0 should be behind the split
- empty; split on epmty (zero-length) text
(?=1) - 1 should be ahead of the split
所以我們有
1000 110011
^^^
|||- 1 should be ahead of split
||-- split here
|--- 0 should be behind the split
問題是您的 Regex Pattern 返回幾個 Matches ,如您在 Here中所見。
您可以改為使用.Matches()
檢索值。
Regex.Matches("100011001110010101110", "(1+0+)").Cast<Match>().Select(x => x.Value);
代碼:
var input = "100011001110010101110";
var results = Regex.Split(input, @"(1+0+)")
.Where(n => !string.IsNullOrEmpty(n))
.ToList();
Console.WriteLine(string.Join("\n", results));
結果:
1000
1100
11100
10
10
1110
Press any key to continue . . .
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.