Find a numeric sequence of a specific length in a string in Ruby -
i need able extract sequence of 8 digits given string. sequence not located in same place string string, , may consist of 8 digits.
examples of strings extracted from:
"123 abcdef 12345678 ghijklmn" "12345678 abcd 1234 efghijkl" "123 4567 12345678" in each of strings above, need 12345678.
i've tried matching regular expression /\d+/, if number appears before 12345678, doesn't work.
you can following regex:
r = / (?<!\d) # negative lookbehind: cannot match digit \d{8} # match 8 digits (?!\d) # negative lookahead: cannot match digit /x "12345678 abcd 1234 efghijkl"[r] #=> "12345678" "x123456789 abcd 1234 efghijkl"[r] #=> nil
Comments
Post a Comment