Reputation: 21128
What is the easiest way to match all lines which follow these rules:
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
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
Reputation: 36110
Just verify that there is at least one non-whitespace character:
^.*\S.*$
Explanation:
^
) til end ($
).*
- any amount of any characters\S
- one non-whitespace characterUpvotes: 2