检查字符串的正则表达式只包含十六进制字符 [英] Regex to check string contains only Hex characters
问题描述
我之前从未做过正则表达式,我看到它们对于使用字符串非常有用。我看了一些教程(例如)但我仍然无法理解如何制作一个简单的Java正则表达式检查字符串中的十六进制字符。
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.
用户将在文本框中输入如下内容: 0123456789ABCDEF
我想知道输入是正确的,否则如果 XTYSPG456789ABCDEF
,当返回false时。
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?
推荐答案
是的,你可以用一个正则表达式:
Yes, you can do that with a regular expression:
^[0-9A-F]+$
说明:
^ 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.
要在Java中使用此正则表达式,您可以调用匹配字符串上的
方法:
boolean isHex = s.matches("[0-9A-F]+");
请注意匹配
只找到完全匹配所以在这种情况下你不需要行锚的起点和终点。看到它在线工作: ideone
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
您可能还想同时允许小写AF,在这种情况下你可以使用这个正则表达式:
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]+$
这篇关于检查字符串的正则表达式只包含十六进制字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!