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]
?
=~ 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.
Ruby regex: Putting It All TogetherRegular expressions can be used with many Ruby methods.
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With