BendEg
BendEg

Reputation: 21128

Match everything besides an empty line or lines containing only whitespaces

What is the easiest way to match all lines which follow these rules:

  1. The line is not empty
  2. The line does not only contain whitespace

I've found an expression which only matches empty lines or those, who only contains white spaces, but I am not able to invert it. This is what I have found: ^\s*[\r\n].

Is it simply possible to invert regular expressions?

Thank you very much!

Upvotes: 2

Views: 2501

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627468

To match non-empty lines, you can use the following regex with multiline mode ON (thanks @Casimir for the character class correction):

^[^\S\r\n]*\S.*$

The end of line is consumed with .* that matches any characters but a newline.

See demo

To just check if the line is not whitespace (but not match it), use a simplified version:

^[^\S\r\n]*\S

See another demo

The [^\S\r\n]* matches 0 or more characters other than non-whitespace and carriage return and line feed symbols. The \S matches a non-whitespace character.

And by the way, if you code in C#, you do not need a regex to check if a string is whitespace, as there is String.IsNullOrWhiteSpace, just split the multiline string with str.Split(new[] {"\r\n"}, StringSplitOptions.None).

Upvotes: 3

ndnenkov
ndnenkov

Reputation: 36110

Just verify that there is at least one non-whitespace character:

^.*\S.*$

See it in action

Explanation:

  • From start (^) til end ($)
  • .* - any amount of any characters
  • \S - one non-whitespace character

Upvotes: 2

Related Questions