Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write a regex to find only numbers with four digits?

Tags:

regex

ruby

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.

like image 494
Lohith MV Avatar asked Aug 09 '11 15:08

Lohith MV


3 Answers

"12345-456-6575 some text 9897".scan(/\b\d{4}\b/)
=> ["6575", "9897"]
like image 56
Dogbert Avatar answered Oct 19 '22 06:10

Dogbert


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"]
like image 35
maerics Avatar answered Oct 19 '22 05:10

maerics


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.

like image 26
Jon Martin Avatar answered Oct 19 '22 04:10

Jon Martin