2

More like a confession.

Had a task that involved invalidating a string if it contained more than five digits (anywhere in the string.)

"No problem", I thought. That sounds like a simple regex!

^(\D*\d?\D*){5}$

Turns out catastrophic backtracking had other ideas, and I revert to my usual "atomic grouping fudge that will hopefully work without me really understanding what's going on" of:

^(?>\D*\d?\D*){5}$

...anyone else shamefully follow this mantra, or am I the only one that hasn't skilled up properly on regexes...

Comments
  • 2
    This sounds like a job for a simple for-loop to me, actually.
    Regular grammar pattern match => regex
    Counting => loop
    Recursive/nested structure => parser
  • 0
    @RememberMe Ah, but a loop just seems so inelegant when a regex can handle the whole lot...
  • 0
    @kenogo I agree in most places, but sometimes it's just so easy to slot one in rather than writing code that it almost begs to be done - HTML5 form validation for example.
  • 0
    5 contiguous digits?
  • 0
    @beegC0de Nope, up to 5 digits anywhere in any combination (so "12 is better than 123" would match, as would "12345 is great", but "123 and 456" would not.)
  • 0
    @AlmondSauce I think a for loop would be a little more understandable to do this man. Unless you're doing code golf?
  • 0
    @beegC0de Yeah, in the end I undid said regex and just looped it. Still wish I was better with them though.
Add Comment