本文介绍了正则表达式检查至少 3 个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个正则表达式只允许字母数字字符.

I have this regex to allow for only alphanumeric characters.

如何检查字符串是否至少包含 3 个字母字符.

How can I check that the string at least contains 3 alphabet characters as well.

我当前的正则表达式,

if(!/^[a-zA-Z0-9]+$/.test(val))

我想强制字符串以确保至少有 3 个连续的字母字符;

I want to enforce the string to make sure there is at least 3 consecutive alphabet characters as well so;

111 // false
aaa1 // true
11a // false
bbc // true
1a1aa // false

推荐答案

要在任何地方强制使用三个字母字符,

To enforce three alphabet characters anywhere,

/(.*[a-z]){3}/i

应该足够了.

编辑.啊,您已经编辑了您的问题,说三个字母字符必须是连续的.我还看到您可能想要强制 all 字符应该与您的接受"字符之一匹配.那么,前瞻可能是最干净的解决方案:

Edit. Ah, you'ved edited your question to say the three alphabet characters must be consecutive. I also see that you may want to enforce that all characters should match one of your "accepted" characters. Then, a lookahead may be the cleanest solution:

/^(?.*[a-z]{3})[a-z0-9]+$/i

请注意,我使用不区分大小写的修饰符 /i 以避免必须编写 a-zA-Z.

Note that I am using the case-insensitive modifier /i in order to avoid having to write a-zA-Z.

替代方案.您可以在此处阅读有关环视断言的更多信息.但在这个阶段,它可能有点超出你的头脑.下面是一个替代方案,您可能会发现根据您已经知道的内容更容易分解:

Alternative. You can read more about lookaround assertions here. But it may be a little bit over your head at this stage. Here's an alternative that you may find easier to break down in terms of what you already know:

/^([a-z0-9]*[a-z]){3}[a-z0-9]*$/i

这篇关于正则表达式检查至少 3 个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:25