Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.
To match empty lines, use the pattern ' ^$ '. To match blank lines, use the pattern ' ^[[:blank:]]*$ '. To match no lines at all, use the command ' grep -f /dev/null '. How can I search in both standard input and in files?
The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a “word boundary”. This match is zero-length. There are three different positions that qualify as word boundaries: Before the first character in the string, if the first character is a word character.
Example: The regex "aa\n" tries to match two consecutive "a"s at the end of a line, inclusive the newline character itself. Example: "a\+" matches "a+" and not a series of one or "a"s. ^ the caret is the anchor for the start of the string, or the negation symbol.
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.
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"
}
String String.trim()
boolean String.isEmpty()
true
if, and only if, length()
is 0
. boolean String.matches(String regex)
Actually in multiline mode a more correct answer is this:
/((\r\n|\n|\r)$)|(^(\r\n|\n|\r))|^\s*$/gm
The accepted answer: ^\s*$
does not match a scenario when the last line is blank (in multiline mode).
Try this:
^\s*$
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.
Full credit to bchr02 for this answer. However, I had to modify it a bit to catch the scenario for lines that have */
(end of comment) followed by an empty line. The regex was matching the non empty line with */
.
New: (^(\r\n|\n|\r)$)|(^(\r\n|\n|\r))|^\s*$/gm
All I did is add ^
as second character to signify the start of line.
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 '/^$/'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With