Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - newline detection in strings

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?

like image 368
Wanderer Avatar asked Sep 23 '26 20:09

Wanderer


2 Answers

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.

like image 67
Anderson Vieira Avatar answered Sep 26 '26 08:09

Anderson Vieira


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
like image 23
Braj Avatar answered Sep 26 '26 09:09

Braj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!