Regex to check string contains only Hex characters

后端 未结 3 1613
孤街浪徒
孤街浪徒 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:08

    Yes, you can do that with a regular expression:

    ^[0-9A-F]+$
    

    Explanation:

    ^            Start of line.
    [0-9A-F]     Character class: Any character in 0 to 9, or in A to F.
    +            Quantifier: One or more of the above.
    $            End of line.
    

    To use this regular expression in Java you can for example call the matches method on a String:

    boolean isHex = s.matches("[0-9A-F]+");
    

    Note that matches finds only an exact match so you don't need the start and end of line anchors in this case. See it working online: ideone

    You may also want to allow both upper and lowercase A-F, in which case you can use this regular expression:

    ^[0-9A-Fa-f]+$
    

提交回复
热议问题