Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: hexadecimal in regular expressions

Tags:

regex

ruby

hex

I need to match an md5 checksum in a regular expression in a Ruby (actually Rails) program. I found out somewhere that I can match hexadecimal strings with \h sequence, but I can't find the link anymore.

I'm using that sequence and my code is working in Ruby 1.9.2. I can make it working even under plain IRB (so it's not a Rails extension).

ruby-1.9.2-p180 :007 > "123abcdf" =~ /^\h+$/; $~
 => #<MatchData "123abcdf"> 
ruby-1.9.2-p180 :008 > "123abcdfg" =~ /^\h+$/; $~
 => nil 

However my IDE mark that expression as wrong and I can't find any reference which cites that sequence.

Is the \h sequence legal in Ruby Regex under any environment/version or should I trust my ide and replace it with something like [abcdef\d]?

like image 854
Fabio Avatar asked Jul 11 '11 22:07

Fabio


People also ask

What does =~ mean in Ruby regex?

=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.

Can you use regex in Ruby?

Ruby regex: Putting It All TogetherRegular expressions can be used with many Ruby methods.

What kind of regex does Ruby use?

A regular expression is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings. Ruby regular expressions i.e. Ruby regex for short, helps us to find particular patterns inside a string. Two uses of ruby regex are Validation and Parsing.

Which regular expression might be used to match hexadecimal numbers?

To match hexadecimal characters, use \x or %0x%. Hexadecimal characters are not affected by the case-insensitive modifier. Example: \x66 or %0x66% matches f, but cannot match F.


1 Answers

Yes it is. Check the official doc for the complete documentation for regex in Ruby.

Note that \h will match uppercase letters too, so it's actually equivalent to [a-fA-F\d]

like image 189
Marc-André Lafortune Avatar answered Oct 04 '22 04:10

Marc-André Lafortune