簡體   English   中英

正則表達式從字符串C#中獲取數字

[英]Regex take numbers from string c#

我想將字符串坐標-54°32'17,420“拆分為每個數字,例如[54,32,17,420]。我正在使用

var longitudeSplitted = Regex.Split(longitutdeString, @"\D+")
    .Where(s => !string.IsNullOrWhiteSpace(s))
    .Distinct()
    .Select(int.Parse)
    .ToList();

它可以正常工作,但是當我有這樣的座標時出現了問題

-11°42'42,420“在這種情況下,我收到的名單只有3個數字[11,42,420]。問題出在哪里?我不太了解這種行為。

正如對該問題的評論中提到的那樣,問題在於對Distinct()的調用。

我給出的示例"-11°42'42,420"包含兩次42 ,因此其中之一被調用Distinct()刪除。

固定表達式為:

var longitudeSplitted = Regex.Split(longitutdeString, @"\D+")
    .Where(s => !string.IsNullOrWhiteSpace(s))
    .Select(int.Parse)
    .ToList();

此外,我原來的正則表達式@"\\D+"無法包含負數的符號。 我不得不重寫為使用.Matches(...)而不是.Split(...)來包含符號。

因此正確的表達是這樣的:

var longitudeSplitted = Regex.Matches(longitutdeString, @"[-+]?\d+").OfType<Match>()
    .Select(match => match.Value)
    .Where(s => !string.IsNullOrWhiteSpace(s))
    .Select(int.Parse)
    .ToList();

這有效:

   var numRegex = new Regex(@"[\+\-0-9]+");
   var numMatches = numRegex.Matches("-11°42'43,440");

我將+/-保留在字符串中(以區分東西方),然后將數字更改為更獨特的內容。 您最終在numMatches.Items中使用4個字符串,每個字符串都可以解析為一個int。 它也適用於“ -11°42'42,420”,但我也想用唯一的數字對其進行測試

這是您可以使用的輔助方法

private static List<int> ExtratctCordinates(string input)
{
    List<int> retObj = new List<int>();
    if(!string.IsNullOrEmpty(input))
    {
        int tempHolder;
        // Use below foreach with simple regex if you want sign insensetive data
        //foreach (Match match in new Regex(@"[\d]+").Matches(input))

        foreach (Match match in new Regex(@"[0-9\+\-]+").Matches(input))
        {
            if (int.TryParse(match.Value, out tempHolder))
            {
                retObj.Add(tempHolder);
            }
        }
    }
    return retObj;          
}

這是樣品電話

List<int> op = ExtratctCordinates("-54°32'17,420\"");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM