Reputation: 143
I am trying to check if a given String contains only line breaks and no characters. I use this method
boolean breaksNoLetters(String msg) {
if (!msg.matches(".*[a-zA-Z]+.*") && msg.contains("\n")) {
return true;
} else {
return false;
}
}
It only does not return false if it contains a line break though.
Upvotes: 2
Views: 15136
Reputation: 310983
One way to go would be to replace \n
with a blank string and check if anything remains:
boolean breaksNoLetters(String msg) {
return !msg.replace("\n", "").isEmpty();
}
EDIT:
With Java 8's streams, it's pretty easy to check that all the characters are, in fact, \n
s:
boolean justLineBreaks = msg.chars().allMatch(c -> c == '\n');
Upvotes: 3
Reputation: 89
Impossible, you wrote
only line breaks and no characters
and line breaks are special character. Step back and think about what problem you want to solve. Is it just to check if a minimum of one single printable character is given? Then trim() the String and check if length() > 0. Else the RegEx above is a good one.
Upvotes: 2
Reputation: 920
If you have to check if a String
contains only one line break and no other characters, use the equals()
method:
public boolean isLineBreak(String line) {
return line.equals(System.getProperty("line.separator"));
}
Another suggest I give you, is to use the System.getProperty("line.separator")
method in order to get the line separator chars, because it's platform independent. For example, UNIX uses \n
and Windows \r\n
. With this method you don't have to care of this.
Java 7 has the System.lineSeparator()
method, which allows you to do the same as System.getProperty("line.separator")
.
Otherwise, if you have to check if a String
contains one or more line break, simply use this:
public boolean isLineBreak(String line) {
return line.matches("[\\n\\r]+");
}
Upvotes: 1
Reputation: 174696
I am trying to check if a given String contains only line breaks and no characters.
String Path1 = "\n\r";
String Path2 = "foo\nbar";
System.out.println(Path1.matches("[\\n\\r]+"));
System.out.println(Path2.matches("[\\n\\r]+"));
"[\\n\\r]+"
matches one or more new line or carriage return characters. Use also the \\f
(form feed) inside the character class if necessary.
Output:
true
false
Upvotes: 6
Reputation: 62854
Why not test it against this regex?
if (msg.matches("[\\n\\r]+")) { }
This regular expression will match all the strings that contain one or more characters from the set of \n
and \r
.
Upvotes: 12