我如何编写一个regex来查找只有4位数字的数字?

时间:2023-02-10 19:28:33

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.

我正在尝试用Ruby编写一个regex来搜索一个只有4位数字的字符串。我在用/\d{4}/但这是给我的数字,有四个以上的数字。

Eg: "12345-456-6575 some text 9897"

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

在这种情况下,我只想要9897和6575,但我也得到了1234,长度为5个字符。

6 个解决方案

#1


15  

"12345-456-6575 some text 9897".scan(/\b\d{4}\b/)
=> ["6575", "9897"]

#2


3  

Try matching on a word boundary (\b) on both sides of the four digit sequence:

在四位数序列两边的字词边界(\b)上尝试配对:

s = '12345-456-6575 some text 9897'
s.scan(/\b\d{4}\b/) # => ["6575", "9897"]

#3


1  

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.

您必须在表达式中再添加一个条件:只有有4位数字时才可以返回数字,而且4位数字之前和之后的字符都必须是非数字。

#4


0  

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

或者更一般地说:除了四位数字前和/或后的数字以外的任何数字:

/\D\d{4}\D/

#5


0  

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

试/[0 - 9][0 - 9][0 - 9][0 - 9][^ 0 - 9]/

#6


-1  

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.

您应该为模式指定一个分隔符。就好像数字前面加上一个空格,REGEX将/\s {4}\s/,希望这能有所帮助。

#1


15  

"12345-456-6575 some text 9897".scan(/\b\d{4}\b/)
=> ["6575", "9897"]

#2


3  

Try matching on a word boundary (\b) on both sides of the four digit sequence:

在四位数序列两边的字词边界(\b)上尝试配对:

s = '12345-456-6575 some text 9897'
s.scan(/\b\d{4}\b/) # => ["6575", "9897"]

#3


1  

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.

您必须在表达式中再添加一个条件:只有有4位数字时才可以返回数字,而且4位数字之前和之后的字符都必须是非数字。

#4


0  

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

或者更一般地说:除了四位数字前和/或后的数字以外的任何数字:

/\D\d{4}\D/

#5


0  

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

试/[0 - 9][0 - 9][0 - 9][0 - 9][^ 0 - 9]/

#6


-1  

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.

您应该为模式指定一个分隔符。就好像数字前面加上一个空格,REGEX将/\s {4}\s/,希望这能有所帮助。