Regex to get first number in string with other characters

前端 未结 10 1482
萌比男神i
萌比男神i 2020-11-30 11:34

I\'m new to regular expressions, and was wondering how I could get only the first number in a string like 100 2011-10-20 14:28:55. In this case, I\'d want it to

相关标签:
10条回答
  • 2020-11-30 11:48

    Try this to match for first number in string (which can be not at the beginning of the string):

        String s = "2011-10-20 525 14:28:55 10";
        Pattern p = Pattern.compile("(^|\\s)([0-9]+)($|\\s)");
        Matcher m = p.matcher(s);
        if (m.find()) {
            System.out.println(m.group(2));
        }
    
    0 讨论(0)
  • 2020-11-30 11:48

    This string extension works perfectly, even when string not starts with number. return 1234 in each case - "1234asdfwewf", "%sdfsr1234" "## # 1234"

        public static string GetFirstNumber(this string source)
        {
            if (string.IsNullOrEmpty(source) == false)
            {
                // take non digits from string start
                string notNumber = new string(source.TakeWhile(c => Char.IsDigit(c) == false).ToArray());
    
                if (string.IsNullOrEmpty(notNumber) == false)
                {
                    //replace non digit chars from string start
                    source = source.Replace(notNumber, string.Empty);
                }
    
                //take digits from string start
                source = new string(source.TakeWhile(char.IsDigit).ToArray());
            }
            return source;
        }
    
    0 讨论(0)
  • 2020-11-30 11:57

    Just

    ([0-9]+) .* 
    

    If you always have the space after the first number, this will work

    0 讨论(0)
  • 2020-11-30 12:01

    Try ^(?'num'[0-9]+).*$ which forces it to start at the beginning, read a number, store it to 'num' and consume the remainder without binding.

    0 讨论(0)
提交回复
热议问题