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

1

0

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
Cutis answered 16/8, 2023 at 19:34 Comment(7)
Why not /\A\d{1,3}(?: \d{3})*\z/?Triley
@WiktorStribiżew good point! You may post it as the answer but I hope someone will explain why my one does not work.Cutis
What was your reasoning?Triley
Side note: Using the Ruby case match operator === is discouraged for regex matching. Use =~ instead.Lafreniere
I think that if you simplify the pattern a bit to \A(?<d>\g<d>)\z then you define the group, and immediately refer to the expression in the defined group and will keep on looping. There is no exit clause.Bargainbasement
@Lafreniere I only need true/false result.Cutis
@WiktorStribiżew in my imagination the integer grows to the left, not to the right, the "first" digits are 100, 10, 1, and the optional growing part had to be the thousands, millions, etc. This was intuitive for me.Cutis
S
1

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

Salmanazar answered 16/8, 2023 at 19:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.