简体   繁体   English

正则表达式将匹配6个字符,只允许数字,前导和尾随空格

[英]Regex that will match 6 characters that only allows digits, leading, and trailing spaces

The regex that I'm trying to implement should match the following data: 我正在尝试实现的正则表达式应该匹配以下数据:

  1. 123456
  2. 12345
  3. 23456
  4. 5
  5. 1
  6.       
  7. 2
  8. 2345

It should not match the following: 不应与以下内容匹配

  1. 12 456
  2. 1234 6
  3. 1 6
  4. 1 6

It should be 6 characters in total including the digits, leading, and trailing spaces. 它应该是6个字符,包括数字,前导和尾随空格。 It could also be 6 characters of just spaces. 它也可以是6个字符的空格。 If digits are used, there should be no space between them. 如果使用数字,则它们之间应该没有空格。

I have tried the following expressions to no avail: 我尝试了以下表达式无济于事:

^\s*[0-9]{6}$
\s*[0-9]\s*

You can just use a *\\d* * pattern with a restrictive (?=.{6}$) lookahead: 您可以使用具有限制性(?=.{6}$)前瞻性的*\\d* *模式:

^(?=.{6}$) *\d* *$

See the regex demo 请参阅正则表达式演示

Explanation: 说明:

  • ^ - start of string ^ - 字符串的开头
  • (?=.{6}$) - the string should only have 6 any characters other than a newline (?=.{6}$) - 字符串应该只有6个换行符以外的任何字符
  • * - 0+ regular spaces ( NOTE to match horizontal space - use [^\\S\\r\\n] ) * - 0 +常规空格( 注意匹配水平空间 - 使用[^\\S\\r\\n]
  • \\d* - 0+ digits \\d* - 0+位数
  • * - 0+ regular spaces * - 0 +常规空间
  • $ - end of string. $ - 结束字符串。

Java demo (last 4 are the test cases that should fail): Java演示 (最后4个是应该失败的测试用例):

List<String> strs = Arrays.asList("123456", "12345 ", " 23456", "     5", // good
"1     ", "      ", "  2   ", " 2345 ",  // good
"12 456", "1234 6", " 1   6", "1    6"); // bad
for (String str : strs)
    System.out.println(str.matches("(?=.{6}$) *\\d* *"));

Note that when used in String#matches() , you do not need the intial ^ and final $ anchors as the method requires a full string match by anchoring the pattern by default. 请注意,在String#matches() ,您不需要intial ^和final $ anchors,因为该方法默认情况下通过锚定模式来要求完整的字符串匹配。

You can also do: 你也可以这样做:

^(?!.*?\d +\d)[ \d]{6}$
  • The zero width negative lookahead (?!.*?\\d +\\d) ensures that the lines having space(s) in between digits are not selected 零宽度负前瞻(?!.*?\\d +\\d)确保未选择数字之间有空格的行

  • [ \\d]{6} matches the desired lines that have six characters having just space and/or digits. [ \\d]{6}匹配六个字符只有空格和/或数字的所需行。

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

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