🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 限制文本中的行数的 Java 正则表达式 > 原文: [https://howtodoinjava.com/regex/java-regex-validate-limit-the-number-of-lines-in-text/](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`** ## 正则表达式的说明 ```java \A # Assert position at the beginning of the string. (?> # Group but don't capture or keep backtracking positions: [^\r\n]* # Match zero or more characters except CR and LF. (?> # Group but don't capture or keep backtracking positions: \r\n? # Match a CR, with an optional following LF (CRLF). | # Or: \n # Match a standalone LF character. ) # End the noncapturing, atomic group. ){0,4} # End group; repeat between zero and four times. [^\r\n]* # Match zero or more characters except CR and LF. \z # Assert position at the end of the string. CR : Carriage Return (\r\n) LF : Line Feed (\n) ``` 在正则表达式之上,验证内容具有最少零行和最多三行。 让我们验证解决方案正则表达式。 #### 零行验证 ```java StringBuilder builder = new StringBuilder(); String regex = "\\A(?>[^\r\n]*(?>\r\n?|\n)){0,3}[^\r\n]*\\z"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(builder.toString()); System.out.println(matcher.matches()); Output : true ``` #### 两行验证 ```java StringBuilder builder = new StringBuilder(); builder.append("Test Line 1"); builder.append("\n"); builder.append("Test Line 2"); builder.append("\n"); String regex = "\\A(?>[^\r\n]*(?>\r\n?|\n)){0,3}[^\r\n]*\\z"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(builder.toString()); System.out.println(matcher.matches()); Output : true ``` #### 六行验证 ```java StringBuilder builder = new StringBuilder(); builder.append("Test Line 1"); builder.append("\n"); builder.append("Test Line 2"); builder.append("\n"); builder.append("Test Line 3"); builder.append("\n"); builder.append("Test Line 4"); builder.append("\n"); builder.append("Test Line 5"); builder.append("\n"); builder.append("Test Line 6"); builder.append("\n"); String regex = "\\A(?>[^\r\n]*(?>\r\n?|\n)){0,3}[^\r\n]*\\z"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(builder.toString()); System.out.println(matcher.matches()); Output : false ``` 我建议您使用上述简单的正则表达式尝试更多的变化。 **祝您学习愉快!**