How do you detect a "word" on a line that contains both letters and numbers?
I need a regex that detects a "word" on a line that contains both letters and numbers and is a certain length, e.g. 812d555c726d10c77b05cd164705665a
. The goal is to detect lines that contain sha1 digests.
If a regex-only is too hard, a Ruby solu开发者_JAVA百科tion is OK.
This should do it:
valid_sha1 = !((str =~ /\b[a-f0-9]{32,}\b/i).nil?)
You can use the following regular expression.
s =~ /^[a-f0-9]{32,32}$/i
Both the other answers require the line begin with the SHA1. If the sha1 can be anywhere in the line, remove the ^
/[a-f0-9]{32}/i
You also don't need the second 32 in the curly braces, as if you only specify one number, it must match exactly that many.
If you really want to require that the word consist of BOTH letters and numbers (as you ask above), then you can use positive lookahead:
sha_array = line.scan(/(?=.{0,31}\d)(?=.{0,31}[a-f])\b[\da-f]{32}\b/i)
The (?=
checks a condition in advance, without consuming anything.
精彩评论