Regex for numbers only

后端 未结 18 2296
野性不改
野性不改 2020-11-22 03:29

I haven\'t used regular expressions at all, so I\'m having difficulty troubleshooting. I want the regex to match only when the contained string is all numbers; but with the

相关标签:
18条回答
  • 2020-11-22 04:17

    This works with integers and decimal numbers. It doesn't match if the number has the coma thousand separator ,

    "^-?\\d*(\\.\\d+)?$"
    

    some strings that matches with this:

    894
    923.21
    76876876
    .32
    -894
    -923.21
    -76876876
    -.32
    

    some strings that doesn't:

    hello
    9bye
    hello9bye
    888,323
    5,434.3
    -8,336.09
    87078.
    
    0 讨论(0)
  • 2020-11-22 04:18

    ^\d+$, which is "start of string", "1 or more digits", "end of string" in English.

    0 讨论(0)
  • 2020-11-22 04:18

    I think that this one is the simplest one and it accepts European and USA way of writing numbers e.g. USA 10,555.12 European 10.555,12 Also this one does not allow several commas or dots one after each other e.g. 10..22 or 10,.22 In addition to this numbers like .55 or ,55 would pass. This may be handy.

    ^([,|.]?[0-9])+$
    
    0 讨论(0)
  • 2020-11-22 04:19

    Use the beginning and end anchors.

    Regex regex = new Regex(@"^\d$");
    

    Use "^\d+$" if you need to match more than one digit.


    Note that "\d" will match [0-9] and other digit characters like the Eastern Arabic numerals ٠١٢٣٤٥٦٧٨٩. Use "^[0-9]+$" to restrict matches to just the Arabic numerals 0 - 9.


    If you need to include any numeric representations other than just digits (like decimal values for starters), then see @tchrist's comprehensive guide to parsing numbers with regular expressions.

    0 讨论(0)
  • 2020-11-22 04:19

    Perhaps my method will help you.

        public static bool IsNumber(string s)
        {
            return s.All(char.IsDigit);
        }
    
    0 讨论(0)
  • 2020-11-22 04:19

    If you want to extract only numbers from a string the pattern "\d+" should help.

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