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,
a source to share
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).
a source to share