如何创建正则表达式以接受不超过 10 位数字? [英] How do I create a regular expression to accept not more than 10 digits?

查看:45
本文介绍了如何创建正则表达式以接受不超过 10 位数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建接受不超过 10 位数字的正则表达式?

How do I create a regular expression to accept not more than 10 digits?

谢谢

推荐答案

既然你问了如何",我会试着一步一步地解释.因为您没有指定您使用的正则表达式风格,所以我将在 PCRE两个 POSIX 正则表达式变体.

Since you've asked "how", I'll try to explain step by step. Because you did not specify which regexp flavor you are using, so I'll provide examples in PCRE and two POSIX regexp variants.

对于简单这样的情况,您应该将正则表达式视为自动化,一次接受一个字符,并在其有效时(接受字符)判断是否有效.在每个字符之后,您可以指定它可能出现的次数,例如(在 PCRE 方言中)*(零次或多次),+(一次或多次)或 {n,m}(来自 nm 次).那么构建过程就变得简单了:

For simple cases like this you should think of regular expression as of automation, accepting one character at a time, and saying whenever it is valid one (accepting the character) or not. And after each character you can specify quantifiers how many times it may appear, like (in PCRE dialect) * (zero or more times), + (one or more time) or {n,m} (from n to m times). Then the construction process becomes simple:

PRCE  | B.POSIX | E.POSIX   | Comments
------+---------+-----------+--------------------------------------------------
^     | ^       | ^         | Unless you are going to accept anything with 10
      |         |           | digits in it, you need to match start of data;
\d    | [0-9]   | [:digit:] | You need to match digits;
{1,10}| \{1,10\}| {1,10}    | You have to specify there is from 1 to 10 of them.
      |         |           | If you also wish to accept empty string — use 0;
$     | $       | $         | Then, data should end (unless see above).

所以,结果是 ^\d{1,10}$, ^[0-9]\{1,10}\$^[:digit:]{1,10}$ 分别.

So, the result is ^\d{1,10}$, ^[0-9]\{1,10}\$ or ^[:digit:]{1,10}$ respectively.

这篇关于如何创建正则表达式以接受不超过 10 位数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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