Warm tip: This article is reproduced from serverfault.com, please click

How to split a Text when detecting String "\n" and a space?

发布于 2020-11-28 06:17:58

for Example

i Have a string like

String example = "Hello\nHow\nAre\nyou today? I Love Pizza"; //

What i want is an Array like this

[Hello, \n, How, \n, Are, \n, you, today? , I , Love, Pizza]

I tried Already

String[] splited = example.split("[\\n\\s]+");// as will a lot of regular exprisions like ("\\n\\r+")  etc.

but they didnt work .

have anyone a solution please ?

Questioner
Moustafa Wafaei Baaj
Viewed
0
Arvind Kumar Avinash 2020-11-29 04:16:43

You can do it simply by using lookbehind (specified by ?<=) or lookahead (specified by ?=) for \n and alternated with \s+ (for whitespace).

Demo:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String example = "Hello\nHow\nAre\nyou today? I Love Pizza"; //
        String[] splited = example.split("(?<=\\n)|(?=\\n)|\\s+");
        System.out.println(Arrays.toString(splited));
    }
}

Output:

[Hello, 
, How, 
, Are, 
, you, today?, I, Love, Pizza]