Bad regex execution

I have a very poorly performing regex part, it is currently causing Firefox, Chrome and IE to freeze for some time.

Here's the reg-ex:

 ^([a-zA-Z0-9]+[/]?)+[a-zA-Z0-9]+$

      

It's kind of a URL, but only needs to match the requested path (not starting with or a forward slash).

Valid examples:

  • Segment
  • Segment / Segment
  • segment / segment / segment (etc.)

Invalid examples:

  • /Segment
  • Segment /
  • Segment / Segment /

Using regex over all three browsers and using two or more forward slashes makes browsers freeze.

This is obviously a poorly formed reg-ex, but can anyone help build a better one?

Thanks,

+2


a source to share


3 answers


Better one would be more deterministic and without capturing groups:

^[a-zA-Z0-9]+(?:/[a-zA-Z0-9]+)*$

      



This way you don't have overlapping groups and you won't grab things unnecessarily.

+7


a source


I think the problem is that with an optional string /

only too many ways can be parsed, in particular any sequence of N alpha algebras can be matched over N-1. What about:

^([a-zA-Z0-9]+[/])*[a-zA-Z0-9]+$

      



i.e. 0 or more (1 + alphamerics-then-slash) followed by one last help (1 + alphamerics). (Of course, you can also specify ?:

immediately after the open peer as other answers if you want the group not to be taken over).

+3


a source


Try

^(?:[^/]+/)*[^/]+$

      

Or if [a-zA-Z0-9]+

really necessary, try

^(?:[a-zA-Z0-9]+/)*[a-zA-Z0-9]+$

      

I personally think one needs to be faster first though

+2


a source







All Articles