Regex to check string contains only Hex characters

后端 未结 3 1595
孤街浪徒
孤街浪徒 2020-12-05 22:58

I have never done regex before, and I have seen they are very useful for working with strings. I saw a few tutorials (for example) but I still cannot understand how to make

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 23:01

    Actually, the given answer is not totally correct. The problem arises because the numbers 0-9 are also decimal values. PART of what you have to do is to test for 00-99 instead of just 0-9 to ensure that the lower values are not decimal numbers. Like so:

    ^([0-9A-Fa-f]{2})+$
    

    To say these have to come in pairs! Otherwise - the string is something else! :-)

    Example:

       (Pick one)
       var a = "1e5";
       var a = "10";
       var a = "314159265";
    

    If I used the accepted answer in a regular expression it would return TRUE.

       var re1 = new RegExp( /^[0-9A-Fa-f]+$/ );
       var re2 = new RegExp( /^([0-9A-Fa-f]{2})+$/ );
    
       if( re1.test(a) ){ alert("#1 = This is a hex value!"); }
       if( re2.test(a) ){ alert("#2 = This IS a hex string!"); }
         else { alert("#2 = This is NOT a hex string!"); }
    

    Note that the "10" returns TRUE in both cases. If an incoming string only has 0-9 you can NOT tell, easily if it is a hex value or a decimal value UNLESS there is a missing zero in front of off length strings (hex values always come in pairs - ie - Low byte/high byte). But values like "34" are both perfectly valid decimal OR hexadecimal numbers. They just mean two different things.

    Also note that "3.14159265" is not a hex value no matter which test you do because of the period. But with the addition of the "{2}" you at least ensure it really is a hex string rather than something that LOOKS like a hex string.

提交回复
热议问题