我有一个非常基本的正则表达式,我只是不知道为什么它不起作用,所以问题是两个部分。为什么我当前的版本不起作用,正确的表达方式是什么。
规则非常简单:
- 必须至少有 3 个字符。
- 如果 % 字符是第一个字符,则必须至少有 4 个字符。
因此,以下情况应按如下方式解决:
- AB - 失败
- ABC-通过
- ABCDEFG - 通过
- % - 失败
- %AB - 失败
- %ABC - 通过
- %ABCDEFG - 通过
- %%AB - 通过
我使用的表达式是:
^%?\S{3}
这对我来说意味着:
^
- 字符串的开始%?
- 贪心检查 0 或 1 % 字符\S{3}
- 3 个非空白字符
The problem is, the %?
for some reason is not doing a greedy check. It's not eating the % character if it exists so the '%AB' case is passing which I think should be failing. Why is the %?
not eating the % character?
Someone please show me the light :)
Edit: The answer I used was Dav below: ^(%\S{3}|[^%\s]\S{2})
Although it was a 2 part answer and Alan's really made me understand why. I didn't use his version of ^(?>%?)\S{3}
because it worked but not in the javascript implementation. Both great answers and a lot of help.