tags:

views:

129

answers:

4

I am trying to make simple regex that will check if a line is blank or not.

Case;

"    some"   // not blank
"   " //blank
"" // blank
+1  A: 

Try this:

^\s*$
Marcelo Cantos
@Adnan, note that `\s` also matches line breaks, so you won't "find" single empty lines inside a string containing successive empty lines.
Bart Kiers
+1  A: 

The most portable regex would be ^[ \t\n]*$ to match an empty string (note that you would need to replace \t and \n with tab and newline accordingly) and [^ \n\t] to match a non-whitespace string.

soulmerge
I'd at least change the single space with the class `[ \t]`
Bart Kiers
@Bart K: Thx ,updated
soulmerge
+7  A: 

The pattern you want is something like this in multiline mode:

^\s*$

Explanation:

  • ^ is the beginning of string anchor
  • $ is the end of string anchor
  • \s is the whitespace character class
  • * is zero-or-more repetition of

In multiline mode, ^ and $ also match the beginning and end of the line.

References


A non-regex alternative

You can also check if a given string line is "blank" (i.e. containing only whitespaces) by trim()-ing it, then checking if the resulting string isEmpty().

In Java, this would be something like this:

if (line.trim().isEmpty()) {
    // line is "blank"
}

The regex solution can also be simplified without anchors (because of how matches is defined in Java) as follows:

if (line.matches("\\s*")) {
    // line is "blank"

API references

polygenelubricants
thank you @polygenelubricants
Adnan
@Adnan: take note of Bart's comment in Marcelo's answer; depending on how you want to handle multiple blank lines, the pattern may change slightly.
polygenelubricants
Well I am reading a file from Java, line by line, so I assume that this will be ok.
Adnan
@polygenelubricants that seems brilliant with line.trim :D
Adnan
@polygenelubricants excellent the codes now executes from 1.6sec to >1sec Thank you.
Adnan
A: 

Here Blank mean what you are meaning.
A line contains full of whitespaces or a line contains nothing.
If you want to match a line which contains nothing then use '/^$/'.

kiruthika