0

I have a string that needs to be read using the Scanner class from the beginning to the \n character. The problem is that the source stream in my case may contain the character \u2028. I know that the Scanner class uses the pattern "\r\n|[\n\r\u2028\u2029\u0085]" to separate lines, for this reason scanner.nextLine() on input line:

1 2 3 4 5 '\u2028' 6 7 8 will only read 1 2 3 4 5

I think that if I could force the scanner to use the pattern [\n\r\u2029\u0085] (default scanner pattern without NEW_LINE symbol) that would solve my problem. How can I read the entire string ignoring the \u2028 symbol ?

6
  • Do you mean nextLine() instead of readLine()? Can't you use scanner.useDelimiter("[\n\r\u2029\u0085]") and then use scanner.next()? Commented Aug 21, 2024 at 14:51
  • @Ivar Brilliant and simple solution. I hadn't thought of that at all. Please format your suggestion as an answer and I will accept it. Thank you very much. Commented Aug 21, 2024 at 15:03
  • Hello Smetana, welcome, String newString = string.replace( "\u2028" , "" ); or String newString = string.replaceAll( "\u2028" , "" ); and work with newString?. Commented Aug 21, 2024 at 15:05
  • @MarcePuente I considered this solution, but it does not suit me, since I read hundreds of gigabytes of text information and then process it. So loading all the data from the stream into memory is not an optimal solution for me. Commented Aug 21, 2024 at 15:10
  • Is'nt this is why we can use .useDelimiter("\\R"). "\\R" Matches any Unicode line-break sequence, that is equivalent to \u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029]. Commented Aug 21, 2024 at 19:05

1 Answer 1

0

The code of @Ivar Brilliant solution:

 String input = "1 2 3 4 5 \u2028 6 7 8\n9 10";
    Scanner scanner = new Scanner(input).useDelimiter(Pattern.compile("[\n\r\u2029\u0085]"));
    if (scanner.hasNext()) {
        String result = scanner.next().replaceAll("\u2028", "");
        System.out.println(result);
    }
    scanner.close();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.