原文: https://howtodoinjava.com/regex/java-regex-validate-limit-the-number-of-lines-in-text/

在此 Java 正则表达式教程中,我们将学习测试输入文本中的行数是否在某个最小和最大限制之间,而不考虑字符串中出现了多少个总字符。

用于匹配行数的正则表达式将取决于用作行分隔符的确切字符或字符序列。 实际上,行分隔符可能会根据操作系统的约定,应用程序或用户首选项等而有所不同。 因此,编写理想的解决方案取决于应支持哪些约定来指示新行的开始。

本教程中讨论的以下解决方案支持标准 MS-DOS/Windows(“\r\n”),旧版 MacOS(“\r”)和 Unix/Linux/BSD/OSX(“\n”)行中断约定。

正则表达式:\\A(?>[^\r\n]*(?>\r\n?|\n)){0,3}[^\r\n]*\\z

正则表达式的说明

  1. \A # Assert position at the beginning of the string.
  2. (?> # Group but don't capture or keep backtracking positions:
  3. [^\r\n]* # Match zero or more characters except CR and LF.
  4. (?> # Group but don't capture or keep backtracking positions:
  5. \r\n? # Match a CR, with an optional following LF (CRLF).
  6. | # Or:
  7. \n # Match a standalone LF character.
  8. ) # End the noncapturing, atomic group.
  9. ){0,4} # End group; repeat between zero and four times.
  10. [^\r\n]* # Match zero or more characters except CR and LF.
  11. \z # Assert position at the end of the string.
  12. CR : Carriage Return (\r\n)
  13. LF : Line Feed (\n)

在正则表达式之上,验证内容具有最少零行和最多三行。 让我们验证解决方案正则表达式。

零行验证

  1. StringBuilder builder = new StringBuilder();
  2. String regex = "\\A(?>[^\r\n]*(?>\r\n?|\n)){0,3}[^\r\n]*\\z";
  3. Pattern pattern = Pattern.compile(regex);
  4. Matcher matcher = pattern.matcher(builder.toString());
  5. System.out.println(matcher.matches());
  6. Output : true

两行验证

  1. StringBuilder builder = new StringBuilder();
  2. builder.append("Test Line 1");
  3. builder.append("\n");
  4. builder.append("Test Line 2");
  5. builder.append("\n");
  6. String regex = "\\A(?>[^\r\n]*(?>\r\n?|\n)){0,3}[^\r\n]*\\z";
  7. Pattern pattern = Pattern.compile(regex);
  8. Matcher matcher = pattern.matcher(builder.toString());
  9. System.out.println(matcher.matches());
  10. Output : true

六行验证

  1. StringBuilder builder = new StringBuilder();
  2. builder.append("Test Line 1");
  3. builder.append("\n");
  4. builder.append("Test Line 2");
  5. builder.append("\n");
  6. builder.append("Test Line 3");
  7. builder.append("\n");
  8. builder.append("Test Line 4");
  9. builder.append("\n");
  10. builder.append("Test Line 5");
  11. builder.append("\n");
  12. builder.append("Test Line 6");
  13. builder.append("\n");
  14. String regex = "\\A(?>[^\r\n]*(?>\r\n?|\n)){0,3}[^\r\n]*\\z";
  15. Pattern pattern = Pattern.compile(regex);
  16. Matcher matcher = pattern.matcher(builder.toString());
  17. System.out.println(matcher.matches());
  18. Output : false

我建议您使用上述简单的正则表达式尝试更多的变化。

祝您学习愉快!