Home > front end >  Ruby regex for string that contains exactly x amount of integers
Ruby regex for string that contains exactly x amount of integers

Time:04-26

I want to craft a ruby regex that matches strings that contain exactly x integer numbers. I want the string to also be able to contain other words as well.

Example: If x = 2, the following should match: "There were 3 cars going over 45 miles per hour"

where the first integer is 3 and the second integer is 45.

CodePudding user response:

You may use the general regex pattern:

^\D*(?:\d \D ){2}$

You may replace the {2} with however many numbers you expect in the string. Here is a working demo.

CodePudding user response:

I would write

str = "There were 3 cars going over 45 miles per hour"
str.scan(/\d /).size == 2
  #=> true

or

str.gsub(/\d /).count == 2
  #=> true

The latter has the advantage that str.gsub(/\d ) returns an enumerator, whereas str.scan(/\d /) creates a temporary array.

See the form of String#gsub that takes an argument but no block, and Enumerable#count.

  • Related