Reputation: 272
I know that similar questions have been asked several times, but the answers I saw are either workarounds or simply incorrect.
The basic problem is fairly simple: A method gives me a string read from a file and I need to check if this string contains newline.
Now to the tricky part: Wikipedia currently lists eight types of characters or character combinations which may, dependent on the system, denote a newline. So checking for the common \n
and \r
, an answer, that I often read, is not the way to go. Walking through the string and compare its characters with System.getProperty("line.separator")
might also fail, since a possible newline representation is `\r\n', that will trigger this comparison twice, though its only one newline.
However, this has to be possible. What option am I missing?
Upvotes: 3
Views: 5361
Reputation: 9049
You can use the regex pattern ^(.*)$
together with the modifier Pattern.MULTILINE
. A method that checks if a string contains any new line character would look like this:
static boolean containsNewLine(String str) {
Pattern regex = Pattern.compile("^(.*)$", Pattern.MULTILINE);
return regex.split(str).length > 0;
}
It splits the string in n parts, depending on the number of newline characters. If the string contains any newline character, the length
will be greater than 0.
Normally ^
and $
will match only the beginning and the end of the string, but you can change this behavior by passing Pattern.MULTILINE
. From the docs:
In multiline mode the expressions ^ and $ match just after or just before, respectively, a line terminator or the end of the input sequence. By default these expressions only match at the beginning and the end of the entire input sequence.
Upvotes: 6
Reputation: 46841
You can try with Regex pattern \r?\n
where \r
is optional.
sample code:
String str = "abc\r\nlmn\nxyz";
Pattern pattern = Pattern.compile("\r?\n");
Matcher matcher = pattern.matcher(str);
int count=0;
while(matcher.find()){
count++;
}
System.out.println(count); // prints 2
Upvotes: 1