开发者

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

开发者 https://www.devze.com 2023-03-26 22:48 出处:网络
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.

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.


or even more generally: anything but a digit before and/or after the four digits:

/\D\d{4}\D/


Try /[0-9][0-9][0-9][0-9][^0-9]/


You should specify a separator for the pattern. As in if the digits would be preceded and followed by a space the REGEX would /\s\d{4}\s/, hope that helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号