开发者

Need help with JavaScript Regular Expression:Regular Expression Too Complex

Following Regula开发者_JAVA技巧r expression ^[0-9A-Za-z]+(\s)*(-?(\s)*[0-9A-Za-z]+)*$ is matching for most of the cases like eg "dsffsd-fdsfds-dasda" but when i give string to be matched as "dsffsd-fdsfds-dasda-dasdas--dasdas-dsfs" im getting error in firebug saying Regular Expression Too Complex.

Any help would be appreciated, Thanks in advance


The regex is falling under Catastrophic Backtracking, which is the reason you get this error. Note that your string isn't matched by the pattern, since the pattern doesn't allow two hyphens: --.

I was able to simplify the pattern to:

/^\w(?:-?\s*\w)*$/

If I did this right, this pattern only allows one way of matching each string, so it shouldn't suffer the same problem.
If you don't need such constrains you can greatly simply the pattern, for example to /^[\w\s\-]*$/.
Note that \w also matched underscores, but it should be easy to correct if needed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜