Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

327
Views
Java Regex for multiline text

I need to match a string against a regex in Java. The string is multiline and therefore contains multiple \n like the followings

String text = "abcde\n"
        + "fghij\n"
        + "klmno\n";
String regex = "\\S*";
System.out.println(text.matches(regex));

I only want to match whether the text contains at least a non-whitespace character. The output is false. I have also tried \\S*(\n)* for the regex, which also returns false.

In the real program, both the text and regex are not hard-coded. What is the right regex to check is a multiline string contains any non-whitespace character?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

The problem is not to do with the multi lines, directly. It is that matches matches the whole string, not just a part of it.

If you want to check for at least one non-whitespace character, use:

"\\s*\\S[\\s\\S]*"

Which means

  • Zero or more whitespace characters at the start of the string
  • One non-whitespace character
  • Zero or more other characters (whitespace or non-whitespace) up to the end of the string
over 4 years ago · Santiago Trujillo Report

0

If you just want to check whether there is at least one non white space character in the string, you can just trim the text and check the size without involving regex at all.

String text = "abcde\n"
    + "fghij\n"
    + "klmno\n";
if (!text.trim().isEmpty()){
    //your logic here
}

If you really want to use regex, you can use a simple regex like below.

String text = "abcde\n"
    + "fghij\n"
    + "klmno\n";
String regex = ".*\\S+.*";
Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
Matcher matcher = pattern.matcher(string);
if (matcher.find()){
    // your logic here
}
over 4 years ago · Santiago Trujillo Report

0

Using String.matches()

!text.matches("\\s*")

Check if the input text consist solely of whitespace characters (this includes newlines), invert the match result with !

Using Matcher.find()

Pattern regexp = Pattern.compile("\\S");
regexp.matcher(text).find()

Will search for the first non-whitespace character, which is more efficient as it will stop on the first match and also uses a pre-compiled pattern.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!