簡體   English   中英

使用Regex C#從字符串中提取值

[英]Extract value from a string using Regex C#

我將知道是否有可能在C#中使用正則表達式從字符串中提取value(int)。

例如,我有一些數據,例如:

“ 124521test45125 100KG10 fdfdfdf”

“ 9856745test123456 60ML450 fdfdfdf”

我想提取包含“ KG”和“ ML”字樣的值,這些數字帶有該字樣前后的數字。

結果將為“ 100KG10”和“ 60ML450”。

他們可能沒有這樣的數字:

“ 124521test45125 100KG fdfdfdf”

這種情況下的結果將是“ 100KG”。

我使用這種方法來提取價值:

public static string Test(string str)
        {
            Regex regex = new Regex(@"???REGEX??");
            Match match = regex.Match(str);
            if (match.Success)
                return match.Value;

            return match;
        }

問題是我剛剛開始學習Regex,我不知道如何只能提取此值。

誰能幫我。

提前致謝

我建議模式是

 [0-9]+(KG|ML)[0-9]*

哪里

  • [0-9]+一位或多位數字
  • (KG|ML)然后是KGML
  • [0-9]*后跟零個或多個數字

實現可以是

public static string Test(string str) {
  // public methods should validate their values; null string is a case
  if (string.IsNullOrEmpty(str))
    return null;

  var match = Regex.Match(str, @"[0-9]+(KG|ML)[0-9]*");

  return match.Success ? match.Value : null;
}

正則表達式

public static string Test(string str)
{
    Regex regex = new Regex(@"\d+(ML|KG)\d*");
    Match match = regex.Match(str);
    if (match.Success)
        return match.Value;

    return null;
}
string[] arrayResult = input.Split(' ').Where(x=>x.Contains("ML") || x.Contains("KG")).ToArray();

string result = string.Join(", ", arrayResult);

這里沒有正則表達式。

編輯:評論后:

    public static bool Condition(string x)
    {
        bool check1 = x.Contains("ML");
        bool check2 = x.Contains("KG");
        bool result = false;

        if(check1)
        {
            x = x.Replace("ML", "");

            var arr = x.Where(y => !char.IsDigit(y));

            result = arr.Count() == 0;
        }
        else if(check2)
        {
            x = x.Replace("KG", "");

            var arr = x.Where(y => !char.IsDigit(y));

            result = arr.Count() == 0;

        }

        return result;
    }

    public static void Main(string[] args)
    {
        string input = "124521teKGst45125 100KG10 fdfdfdf";

        string[] arrayResult = input.Split(' ').Where(x => Condition(x)).ToArray();

        string result = string.Join(", ", arrayResult);
    }

暫無
暫無

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

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