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 ?
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]
that worked thanx for the answer .