简体   繁体   中英

Extract value from a string using Regex C#

I will know if it's possible to extract value(int) from a string with regex in C#.

For example, i have some datas like :

"124521test45125 100KG10 fdfdfdf"

"9856745test123456 60ML450 fdfdfdf"

I will like to extract value which contain caracters "KG" and "ML" with numbers which are before and after this caracters.

The result will be "100KG10" and "60ML450".

It is possible that they don't have numbers after like this :

"124521test45125 100KG fdfdfdf"

The result for this case will be "100KG".

I use this method to extract value :

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

            return match;
        }

The problem is i just start to learn Regex and i don't know how i can extract only this value.

Could any one help me.

Thanks in advance

I suggest the pattern to be

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

where

  • [0-9]+ one or more digits
  • (KG|ML) followed by either KG or ML
  • [0-9]* followed by zero or more digits

The implementation can be

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;
}

RegEx

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);

Here without regex.

EDIT: After the comment:

    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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM