Find and extract a number from a string

前端 未结 29 2735
温柔的废话
温柔的废话 2020-11-22 03:19

I have a requirement to find and extract a number contained within a string.

For example, from these strings:

string test = \"1 test\"
string test1 =         


        
相关标签:
29条回答
  • 2020-11-22 03:36

    Here is another Linq approach which extracts the first number out of a string.

    string input = "123 foo 456";
    int result = 0;
    bool success = int.TryParse(new string(input
                         .SkipWhile(x => !char.IsDigit(x))
                         .TakeWhile(x => char.IsDigit(x))
                         .ToArray()), out result);
    

    Examples:

    string input = "123 foo 456"; // 123
    string input = "foo 456";     // 456
    string input = "123 foo";     // 123
    
    0 讨论(0)
  • 2020-11-22 03:36

    Did the reverse of one of the answers to this question: How to remove numbers from string using Regex.Replace?

    // Pull out only the numbers from the string using LINQ
    
    var numbersFromString = new String(input.Where(x => x >= '0' && x <= '9').ToArray());
    
    var numericVal = Int32.Parse(numbersFromString);
    
    0 讨论(0)
  • 2020-11-22 03:39

    \d+ is the regex for an integer number. So

    //System.Text.RegularExpressions.Regex
    resultString = Regex.Match(subjectString, @"\d+").Value;
    

    returns a string containing the first occurrence of a number in subjectString.

    Int32.Parse(resultString) will then give you the number.

    0 讨论(0)
  • 2020-11-22 03:39

    You can also try this

    string.Join(null,System.Text.RegularExpressions.Regex.Split(expr, "[^\\d]"));
    
    0 讨论(0)
  • 2020-11-22 03:39

    Just use a RegEx to match the string, then convert:

    Match match = Regex.Match(test , @"(\d+)");
    if (match.Success) {
       return int.Parse(match.Groups[1].Value);
    }
    
    0 讨论(0)
  • 2020-11-22 03:43
    var match=Regex.Match(@"a99b",@"\d+");
    if(match.Success)
    {
        int val;
        if(int.TryParse(match.Value,out val))
        {
            //val is set
        }
    }
    
    0 讨论(0)
提交回复
热议问题