Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

java - Regex to check string contains only Hex characters

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 a simple Java regex check for hexadecimal characters in a string.

The user will input in the text box something like: 0123456789ABCDEF and I would like to know that the input was correct otherwise if something like XTYSPG456789ABCDEF when return false.

Is it possible to do that with a regex or did I misunderstand how they work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]+$

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...