简体   繁体   English

需要JavaScript正则表达式的帮助:正则表达式太复杂

[英]Need help with JavaScript Regular Expression:Regular Expression Too Complex

Following Regular 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. 遵循正则表达式^[0-9A-Za-z]+(\\s)*(-?(\\s)*[0-9A-Za-z]+)*$在大多数情况下都是匹配的,例如"dsffsd-fdsfds-dasda" ,但当我将字符串匹配为"dsffsd-fdsfds-dasda-dasdas--dasdas-dsfs" ,萤火虫中出现错误,提示正则表达式太复杂。

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\\-]*$/ . 如果您不需要这样的约束,则可以非常简单地将模式,例如/^[\\w\\s\\-]*$/
Note that \\w also matched underscores, but it should be easy to correct if needed. 请注意, \\w也与下划线匹配,但是如果需要的话,应该很容易更正。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM