I am trying to write a regex in Ruby to search a string for numbers of only four digits. I am using/\d{4}/
but this is giving me number with four and more digits.
Eg: "12345-456-6575 some text 9897
"
In this case I want only 9897
and 6575
but I am also getting 1234
which has a length of five characters.
"12345-456-6575 some text 9897".scan(/\b\d{4}\b/)
=> ["6575", "9897"]
Try matching on a word boundary (\b
) on both sides of the four digit sequence:
s = '12345-456-6575 some text 9897'
s.scan(/\b\d{4}\b/) # => ["6575", "9897"]
You have to add one more condition to your expression: the number can only be returned if there are 4 digits AND both the character before and after that 4-digit number must be a non-number.
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