简体   繁体   English

正则表达式仅7个或13个仅数字字符

[英]Regular expression only 7 or 13 numeric only characters

I am currently using regex: /^\\d+$/ to do numeric only field validation, but I have a need to extend this if possible with the following rules: 我目前正在使用正则表达式: /^\\d+$/进行仅数字字段验证,但是如果可能,我需要使用以下规则进行扩展:

Only 7 numeric characters OR 13 numeric characters 仅7个数字字符 13个数字字符

Examples: 例子:

  • Pass : 1234567 及格 :1234567
  • Pass : 1234567890123 通过 :1234567890123
  • Fail : 12345678 失败 :12345678
  • Fail : 12345678901234 失败 :12345678901234
  • Fail : 12@45!78901234 失败 :12 @ 45!78901234
  • Fail : 12@45!78 失败 :12 @ 45!78
  • Fail : 123 失败 :123

Where did you get stuck in solving this problem? 您在哪里被困在解决这个问题上? You say 你说

Only 7 numeric characters OR 13 numeric characters 仅7个数字字符或13个数字字符

Normally, to match some number of things, we use what are called quantifiers , such as * for zero or more, ? 通常,为了匹配某些事物,我们使用称为量词的词 ,例如*表示零或更多, ? for one or more, {n} for exactly n , or {n,} for n or more, and {n,m} for between n and m . 对于一个或多个, {n}恰好为n ,或者{n,}对于n或更大,并且{n,m}nm之间。

However, there is no single quantifier that means "exactly n or m times". 但是,没有单个量词表示“恰好nm次”。

Therefore, we have to implement the OR in your question using the concept in regexp called alternation , and is represented by the pipe (vertical bar, | ). 因此,我们必须使用正则表达式中的概念Alternate来实现您问题中的OR ,该概念由管道(竖线, | )表示。 This is described in any beginning regexp tutorial . 任何入门的regexp教程都对此进行了描述。

So in your case, the relevant regexp is: 因此,在您的情况下,相关的正则表达式为:

/^(REGEXP-FOR-7-CHARS|REGEXP-FOR-13-CHARS)$/
                     ^  ALTERNATION (PIPE/OR)

As other answers have already suggested, this turns into 正如其他答案已经暗示的那样,这变成了

/^(\d{7}|\d{13})$/

这会起作用

/^(\d{13}|\d{7})$/

You would have to do something like /^\\d{7}(\\d{6})?$/ where 6 = 13 - 7 您将必须执行类似/^\\d{7}(\\d{6})?$/ ,其中6 = 13 - 7

I found this solution a little more flexible then say /^(\\d{7}|\\d{13})$/ since it can also be used without anchors ^$ to match first 7 or first 13 numerical characters. 我发现此解决方案稍微灵活一点,然后说/^(\\d{7}|\\d{13})$/因为它也可以在没有锚^$情况下使用,以匹配前7个或前13个数字字符。 Which maybe useful when you trying to extract data similar to what you are trying to validate. 当您尝试提取与您要验证的数据类似的数据时,这可能很有用。

See this question for more details. 有关更多详细信息,请参见此问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM