Regex accept numeric only. First character can't be 0

前端 未结 4 1072
长情又很酷
长情又很酷 2020-12-13 20:17

I have a textbox that I created using .NET..

By using that textbox, the user only can key in numeric. But not start with 0. start with 1-9. after the user key in th

相关标签:
4条回答
  • 2020-12-13 20:56

    As your code is .NET you should not use regex to parse an Integer. Just use UInt32.TryParse() method

    uint num=0;
    if(UInt32.TryParse(str, out num)){
        Console.WriteLine("Converted '{0}' to {1}.", str, num);   
    }else{
        Console.WriteLine("conversion of '{0}' failed.", value==null? "": value);
    }
    

    Old answer

    This simple regular expression will do it ^[1-9]\d*$

    0 讨论(0)
  • 2020-12-13 21:00

    If you're looking at something like a price, you need to consider that 0.99 is probably perfectly valid. For something like that, I would simply start with a non-complex ^[0-9]*(\.[0-9]{0,2})?$ (again there may be edge cases that may make it more complex like three digits after the decimal point and so on) and allow leading zeroes, since they don't "damage" the value in anyway.

    It it must start with a non zero, just change the initial [0-9]* to a [1-9][0-9]*. For integers only (as seems to be indicated by your added sample data), that would be:

    ^[1-9][0-9]*$
    
    0 讨论(0)
  • 2020-12-13 21:08

    Sometimes the regex wont even work in certain browsers. Therefore here is a similar logic:

    function name(e)
    {
    
    var key = window.event ? e.keyCode : e.which;
    var keychar = String.fromCharCode(key);
    var reg = /\d/;
    
    var textField=document.getElementById("ID").value;
    
    if(key==48)
    {
    if(textField==""||textField==null)
    {
    e.preventDefault();
    return false;
    }
    
    else{
    return true;
    }
    }
    
    else
    {
    var reg = /\d/;
    return reg.test(keychar);
    }
    } 
    
    0 讨论(0)
  • 2020-12-13 21:09

    To match a number starting with any digit but zero:

    ^[1-9][0-9]*$
    

    And if you want to match 0 as well:

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

    remove the last plus if you want a single zero only

    To allow any alpha-numeric after first non-zero:

    ^[1-9a-zA-Z][0-9a-zA-Z]*$
    
    0 讨论(0)
提交回复
热议问题