regex

RegEx that matches positive numbers


I need to write a regex to allow only positive number ( integers or decimals). I have found this:

/^(?!(?:0|0\.0|0\.00)$)[+]?\d+(\.\d|\.\d[0-9])?$/  

but it just accepts up to 2 decimal places. What changes do I have to make, so that it can accept any number of decimal places?

Also where can I find a good tutorial for learning regex.

Thanks beforehand


Solution

  • This would be my way: ^[+]?\d+([.]\d+)?$
    EDIT: If you want to allow something like .23, you could use ^[+]?([.]\d+|\d+([.]\d+)?)$
    EDIT: tchrist insists on this one: allowing 4., you could use ^[+]?([.]\d+|\d+[.]?\d*)$

    Explanation:

    Note: This will not accept a negative number, which is what you ultimately want.