未定义位置只有一个空格的数字的正则表达式 [英] Regular expression for numbers with only one space in undefined positions

查看:27
本文介绍了未定义位置只有一个空格的数字的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个正则表达式来验证数字,并且在未定义的位置仅用一个空格?

i am trying to write a regular expression to validate the numbers with only one space in undefined places?

最多12个字符(带一个空格)或最多11个字符(不带空格).

Maximum of 12 characters with one space or Maximum of 11 characters without spaces.

例如:"25897 569874","5674","65783987665","435 6523"

Ex: '25897 569874','5674','65783987665','435 6523'

我尝试使用 ^ [0-9] {0,12} $ .这不是完美的方法,因为我不知道如何放置空格及其数量.

i have tried with ^[0-9]{0,12}$.this is not perfect cause I don't know how to place the spaces and its counts.

推荐答案

您可以使用此正则表达式:

You can use this regex:

^(?:\d{1,11}|(?=\d+ \d+$)[\d ]{3,12})$

\ d {1,11} 将从1到11位数字匹配,没有空格.

\d{1,11} will match from 1 to 11 digits without space.

(?= \ d + \ d + $)[\ d] {3,12} 最多可以匹配11位数字,中间是一个空格.空格不能是前导或尾随的,因此'23'将被拒绝.

(?=\d+ \d+$)[\d ]{3,12} will match up to 11 digits with one space somewhere in the middle. The space cannot be leading or trailing, so ' 23' will be rejected.

  • (?= \ d + \ d + $)是先行匹配的一个或多个数字,然后匹配一个空格,然后一个或多个数字,然后匹配字符串的末尾.它确保仅出现一个空格,并且该空格不会在前或后出现.前瞻还隐式地确认字符串中至少包含3个字符.
  • [\ d] {3,12} 将确保字符串仅包含数字或空格,最多12个数字或空格.重复次数的下限可以设置为3或更低,因为前瞻已暗示了这一点.
  • (?=\d+ \d+$) is a look-ahead that matched one or more digit, then a space, then one or more digit, then anchor the end of string. It guarantees only one space will appear and the space will not be leading or trailing. The look-ahead also implicitly confirms that there are at least 3 characters in the string.
  • [\d ]{3,12} will guarantee the string only contains digits or space, and up to 12 of them. The lower bound of number of repetition can be set to 3 or lower, since it has been implied by the look-ahead.

这两个约束共同确保文本包含1到11个数字,并在数字之间的任意位置包含一个可选空格.

The 2 constraints together guarantees that text contains from 1 to 11 digits and an optional space at arbitrary position in between the digits.

要允许前导空格,但拒绝单个空格,空字符串和尾随空格:

To allow leading space, but reject single space, empty string and trailing spaces:

^(?:\d{1,11}|(?=\d* \d+$)[\d ]{2,12})$

同样,前瞻至少包含2个字符,因此重复次数可以设置为2个或更少.

Again, the look-ahead implies at least 2 characters, so the number of repetitions can be set to 2 or lower.

这篇关于未定义位置只有一个空格的数字的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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