如何使用正则表达式匹配任何字符串,但至少为 3 个字符? [英] How do I use a regular expression to match any string, but at least 3 characters?

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

问题描述

我不是正则表达式专家,但我的要求很简单:我需要匹配至少有 3 个或更多匹配字符的字符串.

例如,我们有字符串hello world"并将其与以下内容匹配:

"he" =>false//只有 2 个字符hel" =>true//找到 3 个字符匹配

解决方案

这是 python 正则表达式,但它可能也适用于其他实现它的语言.

我想这取决于你认为一个角色是什么.如果是字母、数字和下划线:

\w{3,}

如果只是字母和数字:

[a-zA-Z0-9]{3,}

Python 也有一个 regex 方法来返回字符串中的所有匹配项.

<预><代码>>>>进口重新>>>re.findall(r'\w{3,}', '这是一个长字符串,是的.')['this', 'long', 'string', 'yes']

I am not a regex expert, but my request is simple: I need to match any string that has at least 3 or more characters that are matching.

So for instance, we have the string "hello world" and matching it with the following:

"he" => false // only 2 characters
"hel" => true // 3 characters match found

解决方案

This is python regex, but it probably works in other languages that implement it, too.

I guess it depends on what you consider a character to be. If it's letters, numbers, and underscores:

\w{3,}

if just letters and digits:

[a-zA-Z0-9]{3,}

Python also has a regex method to return all matches from a string.

>>> import re
>>> re.findall(r'\w{3,}', 'This is a long string, yes it is.')
['This', 'long', 'string', 'yes']

这篇关于如何使用正则表达式匹配任何字符串,但至少为 3 个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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