简体   繁体   English

Ruby,检查字符串是否都是有效的十六进制字符?

[英]Ruby, check if string is all valid hex characters?

I have to check if a 4 character string is all valid hex, I found another question which demonstrates exactly what I want to do but it's Java: Regex to check string contains only Hex characters 我必须检查一个4字符的字符串是否都是有效的十六进制,我发现另一个问题,它确切地说明我想要做什么,但它是Java: 检查字符串只包含十六进制字符的正则表达式

How can I accomplish this? 我怎么能做到这一点?

I read the ruby docs for Regular expressions, but I don't understand how to return a true or false based on this match? 我阅读了正则表达式的ruby文档,但是我不明白如何基于这个匹配返回true或false?

In ruby regex \\h matches a hex digit and \\H matches a non-hex digit. 在ruby中,正则表达式\\ h匹配十六进制数字,\\ H匹配非十六进制数字。

So !str[/\\H/] is what you're looking for. 所以!str[/\\H/]正是你要找的。

if str =~ /^[0-9A-F]+$/

does the trick. 诀窍。 If you want case insensitive then: 如果你想要不区分大小写,那么:

str =~ /^[0-9A-F]+$/i
pattern = /^[[:xdigit:]]+$/

And then just check: 然后检查:

if  pattern === your_string
if /^[[:xdigit:]]+$/ === your_string

or with 或者

if your_string.match?(/^[[:xdigit:]]+$/)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM