最有效的正则表达式,用于检查字符串是否包含至少3个字母数字字符 [英] Most efficient regex for checking if a string contains at least 3 alphanumeric characters

查看:766
本文介绍了最有效的正则表达式,用于检查字符串是否包含至少3个字母数字字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个正则表达式:

(?:.*[a-zA-Z0-9].*){3}

我用它来查看字符串中是否至少包含3个字母数字字符。它似乎有效。

I use it to see if a string has at least 3 alphanumeric characters in it. It seems to work.

它应匹配的字符串示例:

Examples of strings it should match:

'a3c'
'_0_c_8_'
' 9 9d '

但是,我需要它更快地工作。有没有更好的方法来使用正则表达式匹配相同的模式?

However, I need it to work faster. Is there a better way to use regex to match the same patterns?

编辑:
我最终使用这个正则表达式用于我的目的:

(?:[^a-zA-Z0-9]*[a-zA-Z0-9]){3}

(不需要修饰符)

推荐答案

效率最高正则表达式方法是使用对比原则,即使用相反的字符类旁边侧。这是一个正则表达式,可用于检查字符串是否有3个拉丁字母或数字:

The most efficient regex approach is to use the principle of contrast, i.e. using opposite character classes side by side. Here is a regex that can be used to check if a string has 3 Latin script letters or digits:

^(?:[^a-zA-Z0-9]*[a-zA-Z0-9]){3}

查看演示

In如果你需要一个完整的字符串匹配,你需要附加。* (或。* $ 如果你想要保证你将匹配所有直到字符串/行的结尾),但在我的regexhero测试中,。* 产生更好的性能):

In case you need a full string match, you will need to append .* (or .*$ if you want to guarantee you will match all up to the end of string/line), but in my tests on regexhero, .* yields better performance):

^(?:[^a-zA-Z0-9]*[a-zA-Z0-9]){3}.*

此外,很大程度上取决于引擎。 PCRE具有自动优化功能,包括自动拥有(即它将 * 转换为 * + (?:[^ a-zA-Z0-9] * + )。

Also, a lot depends on the engine. PCRE has auto-optimizations in place that consists in auto-possessification (i.e. it turns the * to *+ in (?:[^a-zA-Z0-9]*+).

参见有关密码验证优化的更多详细信息

这篇关于最有效的正则表达式,用于检查字符串是否包含至少3个字母数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆