Nakilon
Nakilon

Reputation: 35102

Regex for integer with spaces every three digits throws "never ending recursion"

I want to validate the string to be an integer of such format of undefined length.

/\A (?<d> ( ( (\g<d>[[:space:]])? \d)? \d)? \d) \z/x === "12 123 123"

but it throws

SyntaxError: never ending recursion

Upvotes: 0

Views: 78

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627469

It seems you can use

/\A\d{1,3}(?: \d{3})*\z/

Or, to support any kind of whitespace:

/\A\d{1,3}(?:[[:space:]]\d{3})*\z/
/\A\d{1,3}(?:\p{Z}\d{3})*\z/

Details:

  • \A - start of a string
  • \d{1,3} - one, two or three digits
  • (?:[[:space:]]\d{3})* - zero or more occurrences of a whitespace and then three digits
  • \z - end of string.

See the Rubular demo.

Also, see Fastest way to check if a string matches a regexp in ruby? how to check if a string matches a regex in Ruby. In short, it is your_pattern.match?(your_string).

Upvotes: 1

Related Questions