I am trying to make a regular expression for string test.
Basically what I want is something-something
.
'a' ===> TRUE
'abc' ===> TRUE
'a-b' ===> TRUE
'-' ===> FALSE
'a-' ===> FALSE
'-b' ===> FALSE
So the first version of this regexp is born.
/^[\w]+[-\s]?[\w]+$/
It is working fine, but it won't pass if the string is only one letter.
'a', failed
So I modified the pattern
^[\w]+([-\s]?[\w]+)*$
It's working but the browser hangs if the tested string is long (like 20+ letters), and yes, I know what's going on there, the Catastrophic Backtracking
.
So in this scenario, how can I improve it?
UPDATE:
I think I missed one scenario, it should also support the repeat groups.
aaa aaa aaa aaa ===> TRUE
aaa-aaa aaa-aaa ===> TRUE
That's why I made the group with brackets.