检测字符串“\n”和空格时如何分割文本?

ttcibm8c  于 2021-07-08  发布在  Java
关注(0)|答案(3)|浏览(325)

例如
我有一根绳子

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

我想要的是这样一个数组

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

我已经试过了

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

但他们没有工作。
有人有解决办法吗?

zxlwwiss

zxlwwiss1#

// 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);
    }
}

结果:

1. Hello
 2. \n
 3. How
 4. \n
 5. Are
 6. \n
 7. you
 8. today?
 9. I
10. Love
11. Pizza
a9wyjsp7

a9wyjsp72#

只需使用lookback(由 ?<= )或向前看(由 ?= )为了 \n 交替着 \s+ (用于空格)。
演示:

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));
    }
}

输出:

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

6mw9ycah3#

您可以拆分Assert一个换行符序列 \R 或匹配水平空格字符 \h 使用替换 | ```
(?=\R)|(?<=\R)|\h

java演示
例如

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);
}

输出

Hello
newline
How
newline
Are
newline
you
today?
I
Love
Pizza

相关问题