[英]Extract groups of numbers inside brackets using RegEx
假設我有以下文本塊:
/HDMAreaCoverageValue CIP3BeginPrivate
/HDMZones <</HDMInkC [0.000000][0.000002][0.000400][0.006000]
/HDMInkM [0.006000][0.086000]
/HDMInkB [0.000000][0.000002][0.000400]
>> def
我正在嘗試僅提取方括號內的數字-但是,按照我目前的模式,結果,我得到的全都是花括號。 我目前正在嘗試:
Regex ColorValueRegex = new Regex("HDMZones([0-9,]{1,})+>>");
這種模式有什么問題? 我可以看到我正在做的是從稍后提供的數據中提取數字\\逗號(或點)。
我的代碼:
foreach (var data in ValidFiles)
{
Regex ColorValueRegex = new Regex("HDMZones([0-9,]{1,})+>>");
var RegexAux2 = ColorValueRegex.Match(data);
//HDMZonesNumbers.Add(RegexAux2.Groups[1].ToString().Replace("HDMZones <</", "").Replace("<</", "").Replace("/", ""));
string pattern = @"([\d]+[,.]{0,1})+";
string NumbersCleaned = Regex.Match(RegexAux2.ToString(), pattern).Value;
}
帶有注釋的部分是因為提取后,我將結果字符串添加到列表中。 我希望提取一個像這樣的字符串:
[0.000000][0.000002][0.000400][0.006000][0.006000][0.086000]
我已經嘗試使用StackOverflow提供的許多示例,但是'em都沒有滿足我的需求。 在編寫此代碼之前,我已經使它工作了,但是在一個巨大的foreach循環中-現在我正在單獨處理數據。 任何幫助將不勝感激。 謝謝
如果您只想匹配數字,建議您使用以下正則表達式。
正則表達式: \\[[\\d.]*\\]
說明:
digits
, dot
和square brackets []
並將其作為匹配返回。 在C#中嘗試:
Regex ColorValueRegex = new Regex(@"\[[0-9\.]+\]");
這給出了您想要的答案。
我如何實現結果的:我決定將請求的模式分為兩個正則表達式。 一種是只提取帶有一些文本的數字,另一種是將數字放入方括號內(方括號內)。 然后,稍后我將[[替換為空白,]用定界符|替換。 這樣,我可以拆分為一個數組並執行一些我需要的操作。 代碼如下:
public void ColorValueExtraction()//Processing all colors values
{
StringBuilder sb = new StringBuilder(); //Creating a StringBuilder object to append later
string ColorsWithBrackets = string.Empty;
foreach (var data in ValidFiles) //data means a file - lots of text
{
Regex ValuesRegex = new Regex("HDMZones(.*)>>"); //Extracting only content between HDMZones and >>
var RegexAux2 = ValuesRegex.Match(data); //Match my pattern on data
ColorsWithBrackets = RegexAux2.Groups[1].ToString();
ColorsWithBrackets = ColorsWithBrackets.Replace("HDMZones <</", "").Replace("<</", "").Replace("/", ""); //Replacing a few things
var pattern = @"\[(.*?)\]"; //Extract numbers and brackets only
var query = ColorsWithBrackets;
var matches = Regex.Matches(query, pattern);
foreach (Match m in matches) //Looping on matches ,numbers found
{
string aux2 = string.Empty; //auxiliar string
aux2 = m.Groups[1].ToString();//auxiliar string receives the match to string
aux2 = Regex.Replace(aux2, @"\s+", "|"); //replacing all spaces with | , to be used as delimiter in other method
sb.Append(aux2); //each iteration appends to StringBuilder aux2 - so, in the end, sb will have all numbers from the respective file
}
HDMZonesNumbersLst.Add(sb.ToString()); //Adding each collection of numbers to a position in the list
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.