在正则表达式中设置最小和最大字符 [英] Set minimum and maximum characters in a regular expression

查看:238
本文介绍了在正则表达式中设置最小和最大字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个正则表达式,该表达式可以匹配任意数量的字母和任意数量的字母之间的单个空格.我希望该正则表达式也可以强制执行最小和最大字符数,但是我不确定如何做到这一点(或者如果可能的话).

I've written a regular expression that matches any number of letters with any number of single spaces between the letters. I would like that regular expression to also enforce a minimum and maximum number of characters, but I'm not sure how to do that (or if it's possible).

我的正则表达式是:

[A-Za-z](\s?[A-Za-z])+

我意识到它只匹配围绕一个空格的两组字母,因此我对其进行了少许修改以解决该问题.原来的问题还是一样.

I realized it was only matching two sets of letters surrounding a single space, so I modified it slightly to fix that. The original question is still the same though.

是否有一种方法可以强制执行最少三个字符且最多30个字符?

Is there a way to enforce a minimum of three characters and a maximum of 30?

推荐答案

就像+表示一个或多个,您可以使用{3,30}匹配3到30

Just like + means one or more you can use {3,30} to match between 3 and 30

例如[a-z]{3,30}匹配3到30个小写字母

For example [a-z]{3,30} matches between 3 and 30 lowercase alphabet letters

Pattern类的文档

X{n,m}    X, at least n but not more than m times

在您的情况下,可以通过以下方式匹配3-30个字母,后跟空格:

In your case, matching 3-30 letters followed by spaces could be accomplished with:

([a-zA-Z]\s){3,30}

如果需要尾随空格,则可以使用:(2-29乘以字母+空格,然后是字母)

If you require trailing whitespace, if you don't you can use: (2-29 times letter+space, then letter)

([a-zA-Z]\s){2,29}[a-zA-Z]

如果您希望空格算作字符,则需要将该数字除以2以获得

If you'd like whitespaces to count as characters you need to divide that number by 2 to get

([a-zA-Z]\s){1,14}[a-zA-Z]

如果结尾的空白是可选的,则可以在最后一个末尾添加\s?.这些都在 RegexPlanet

You can add \s? to that last one if the trailing whitespace is optional. These were all tested on RegexPlanet

如果您希望整个字符串在3到30个字符之间,则可以先行使用,在RegExp的开头添加(?=^.{3,30}$)并消除其他大小限制

If you'd like the entire string altogether to be between 3 and 30 characters you can use lookaheads adding (?=^.{3,30}$) at the beginning of the RegExp and removing the other size limitations

所有这些,说实话,我可能只是测试String.length属性.更具可读性.

All that said, in all honestly I'd probably just test the String's .length property. It's more readable.

这篇关于在正则表达式中设置最小和最大字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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