Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a numeric sequence of a specific length in a string in Ruby

Tags:

ruby

I need to be able to extract a sequence of exactly 8 digits from a given string. The sequence is not located in the same place from string to string, and may consist of any 8 digits.

Examples of strings to be extracted from:

"123 ABCDEF 12345678 GHIJKLMN"
"12345678 ABCD 1234 EFGHIJKL"
"123 4567 12345678"

In each of the strings above, I need just the 12345678.

I've already tried matching the regular expression /\d+/, but if any number appears before the 12345678, it doesn't work.

like image 549
bgue Avatar asked Dec 03 '25 16:12

bgue


2 Answers

You can do that with the following regex:

r = /
    (?<!\d) # negative lookbehind: cannot match a digit
    \d{8} # match 8 digits
    (?!\d) # negative lookahead: cannot match a digit
    /x

 "12345678 ABCD 1234 EFGHIJKL"[r]
   #=> "12345678"
 "x123456789 ABCD 1234 EFGHIJKL"[r]
   #=> nil
like image 87
Cary Swoveland Avatar answered Dec 06 '25 06:12

Cary Swoveland


Try specifying that you need exactly eight digits:

/(?<!\d)\d{8}(?!\d)/

Edit: Add negative look-behind and negative look-ahead to only match exactly 8 digit sequences. Credit: @CarySwoveland.

like image 32
Alex Pan Avatar answered Dec 06 '25 06:12

Alex Pan