正则表达式检查字符串只包含十六进制字符 [英] Regex to check string contains only Hex characters

查看:41
本文介绍了正则表达式检查字符串只包含十六进制字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前从未使用过正则表达式,我发现它们对于处理字符串非常有用.我看到了一些教程(例如),但我仍然无法理解如何制作一个简单的 Java 正则表达式检查字符串中的十六进制字符.

用户将在文本框中输入类似:0123456789ABCDEF 并且我想知道输入是否正确,否则如果返回 false 时类似 XTYSPG456789ABCDEF.

是否可以使用正则表达式来做到这一点,还是我误解了它们的工作原理?

解决方案

是的,您可以使用正则表达式做到这一点:

<前>^[0-9A-F]+$

说明:

<前>^ 行首.[0-9A-F] 字符类:0 到 9 或 A 到 F 中的任何字符.+ 量词:上述一项或多项.$ 行尾.

<小时>

要在 Java 中使用此正则表达式,您可以例如在字符串上调用 matches 方法:

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

请注意,matches 只会找到完全匹配的内容,因此在这种情况下您不需要行首和行尾锚点.在线查看它的运行情况:ideone

您可能还希望允许大写和小写 A-F,在这种情况下,您可以使用此正则表达式:

<前>^[0-9A-Fa-f]+$

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?

解决方案

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

这篇关于正则表达式检查字符串只包含十六进制字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆