Find and extract a number from a string

前端 未结 29 3203
温柔的废话
温柔的废话 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:58

    An interesting approach is provided here by Ahmad Mageed, uses Regex and StringBuilder to extract the integers in the order in which they appear in the string.

    An example using Regex.Split based on the post by Ahmad Mageed is as follows:

    var dateText = "MARCH-14-Tue";
    string splitPattern = @"[^\d]";
    string[] result = Regex.Split(dateText, splitPattern);
    var finalresult = string.Join("", result.Where(e => !String.IsNullOrEmpty(e)));
    int DayDateInt = 0;
    
    int.TryParse(finalresult, out DayDateInt);
    

提交回复
热议问题