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.
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
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.
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