Regex to match 2 digits, optional decimal, two digits

后端 未结 11 1335
时光取名叫无心
时光取名叫无心 2020-11-30 09:29

I\'ve spent half an hour trying to get this, maybe someone can come up with it quickly.

I need a regular expression that will match one or two digits, followed by an

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

    Following is Very Good Regular expression for Two digits and two decimal points.

    [RegularExpression(@"\d{0,2}(\.\d{1,2})?", ErrorMessage = "{0} must be a Decimal Number.")]
    
    0 讨论(0)
  • 2020-11-30 10:18

    EDIT: Changed to fit other feedback.

    I understood you to mean that if there is no decimal point, then there shouldn't be two more digits. So this should be it:

    \d{0,2}(\.\d{1,2})?
    

    That should do the trick in most implementations. If not, you can use:

    [0-9]?[0-9]?(\.[0-9][0-9]?)?
    

    And that should work on every implementation I've seen.

    0 讨论(0)
  • 2020-11-30 10:23

    you can use

    let regex = new RegExp( ^(?=[0-9.]{1,${maxlength}}$)[0-9]+(?:\.[0-9]{0,${decimal_number}})?$ );

    where you can decide the maximum length and up to which decimal point you want to control the value

    Use ES6 String interpolation to wrap the variables ${maxlength} and ${decimal_number}.

    0 讨论(0)
  • 2020-11-30 10:25

    A previous answer is mostly correct, but it will also match the empty string. The following would solve this.

    ^([0-9]?[0-9](\.[0-9][0-9]?)?)|([0-9]?[0-9]?(\.[0-9][0-9]?))$
    
    0 讨论(0)
  • 2020-11-30 10:25

    Try this

    \d{1,2}\.?(\.\d{1,2})?
    
    0 讨论(0)
提交回复
热议问题