regex allow only numbers or empty string

后端 未结 6 534
失恋的感觉
失恋的感觉 2021-02-05 04:30

Can someone help me create this regex. I need it to check to see if the string is either entirely whitespace(empty) or if it only contains positive whole numbers. If anything el

相关标签:
6条回答
  • 2021-02-05 04:37

    You're looking for:

    /^(\s*|\d+)$/
    

    If you want a positive number without leading zeros, use [1-9][0-9]*

    If you don't care about whitespaces around the number, you can also try:

    /^\s*\d*\s*$/
    

    Note that you don't want to allow partial matching, for example 123abc, so you need the start and end anchors: ^...$.
    Your regex has a common mistake: ^\s*|\d+$, for example, does not enforce a whole match, as is it the same as (^\s*)|(\d+$), reading, Spaces at the start, or digits at the end.

    0 讨论(0)
  • 2021-02-05 04:41

    Kobi has a good answer but technically you don't have to capture it (unless you're going to do something the output)

    /^[\s\d]+$/
    

    Or if you don't care if the string is completely empty (i.e. "")

    /^[\s\d]*$/
    

    To clarify I understood the original question to mean whitespace in the string should be ignored.

    0 讨论(0)
  • 2021-02-05 04:46

    This helped me. It matches empty string and any number you enter.

    /^(|\d)+$/
    

    Try here if you want: regex101.com

    0 讨论(0)
  • 2021-02-05 04:55

    You can try it-

    /^\d*$/
    

    To match with white space-

    /^[\s\d\s]*$/
    
    0 讨论(0)
  • 2021-02-05 05:00

    To match a number or empty string '' i.e the user has not entered any input do this

    (^[0-9]+$|^$)
    

    To match a number, an empty string, or a white space character

    (^[0-9]+$|^$|^\s$)
    

    Test this on regex101

    0 讨论(0)
  • 2021-02-05 05:00
    ^\d+([\.\,][0]{2})?$
    

    I found this worked for me. Allow any whole number, but only a decimal of .00

    Pass

    • 999 90
    • 100
    • 100.00
    • 101.00
    • 1000.00

    Fails

    • 101.01
    • 1000.99

    Try it at http://regexpal.com/

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