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 split asserting either a newline sequence \R on the left or right, or match a horizontal whitespace char \h using an alternation |
(?=\\R)|(?<=\\R)|\\h
For example
String example = "Hello\nHow\nAre\nyou today? I Love Pizza"; //
String[] splited = example.split("(?=\\R)|(?<=\\R)|\\h");
for (String element : splited) {
if (element.equals("\n")) element = "newline";
System.out.println(element);
}
Output
Hello
newline
How
newline
Are
newline
you
today?
I
Love
Pizza
// Split on the following:
// look ahead for '\n' which is preceded by a character that is not '\n'
// OR look ahead for a character that is not '\n' preceded by '\n'
// OR a single space.
String regex = "(?=\\n)(?<!\\n)|(?!\\n)(?<=\\n)| ";
String example = "Hello\nHow\nAre\nyou today? I Love Pizza";
// This is the array that you want.
String[] splited = example.split(regex);
// This is just to display the contents of 'splited'.
int count = 0;
for (String part : splited) {
count++;
if (part.equals("\n")) {
// Rather than print the actual newline, print its escape sequence
System.out.printf("%2d. \\n%n", count);
}
else {
System.out.printf("%2d. %s%n", count, part);
}
}
Result:
1. Hello
2. \n
3. How
4. \n
5. Are
6. \n
7. you
8. today?
9. I
10. Love
11. Pizza
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]