HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Java Regular Expressions / Java Regex to limit the number of lines in text

Java Regex to limit the number of lines in text

In this java regex tutorial, we will learn to test whether number of lines in input text is between some minimum and maximum limit, without regard for how many total characters appear in the string.

The regex for matching number of lines will depend on the exact characters or character sequences used as line separators. In practice, line separators can vary depending on your operating system’s convention, application or user preferences, and so on. Writing an ideal solution therefore depends on what conventions for indicating the start of a new line should be supported.

The following solution discussed in this tutorial supports the standard MS-DOS/Windows (“\r\n”), legacy Mac OS (“\r”), and Unix/Linux/BSD/OS X (“\n”) line break conventions.

Regex : \\A(?>[^\r\n]*(?>\r\n?|\n)){0,3}[^\r\n]*\\z

Explanation of Regex

\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)

Above regular expression validate that content has minimum zero lines and maximum 3 lines. Let’s verify the solution regex.

Verify with zero lines

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

Verify with two lines

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

Verify with six lines

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

I will advise to play with above simple regular expression to try more variation.

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Java Regex Tutorial

  • Java Regex – Introduction
  • Java Regex : Alphanumeric
  • Java Regex : Credit Card Numbers
  • Java Regex : Canadian Postcodes
  • Java Regex : Currency Symbol
  • Java Regex : Date Format
  • Java Regex : Email Address
  • Java Regex : Password
  • Java Regex : Greek Characters
  • Java Regex : ISBNs
  • Java Regex : Min/Max Length
  • Java Regex : No. of Lines
  • Java Regex : No. of Words
  • Java Regex : SSN
  • Java Regex : UK Postal Codes
  • Java Regex : US Postal Codes
  • Java Regex : Trademark Symbol
  • Java Regex : Intl Phone Numbers
  • North American Phone Numbers

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces