繁体   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