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

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

问题描述

我写了一个正则表达式,它匹配任意数量的字母,这些字母之间有任意数量的单个空格。我希望这个正则表达式也强制执行最小和最大字符数,但我不知道该怎么做(或者如果可能的话)。

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 min and max number of characters, but I'm not sure how to do that (or if it's possible).

My正则表达式为:

[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.

有没有办法强制执行至少三个字符,最多三个字符?

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

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

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

来自模式类的文档


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个字符之间,您可以使用前瞻性添加(?= ^。{3,30} $) RegExp并删除其他大小限制

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天全站免登陆