【问题标题】:How to split a Text when detecting String "\n" and a space?检测字符串“\n”和空格时如何拆分文本?
【发布时间】:2021-03-10 19:19:45
【问题描述】:

举例

我有一个类似的字符串

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.

但他们没有工作。

请问有人有解决办法吗?

【问题讨论】:

  • \s 匹配包含\n\r 甚至\t 的空格。因此,如果您不希望它在\n 上拆分,请不要使用它。请改用" "。现在要处理\n,您可以使用look-around 机制来描述在它之前或之后有\n 的地方。
  • 输出应该在today? I 之后包含一个空格?
  • @Pshemo ,我已经尝试过 " " ,但什么也没发生,它用空格分隔,但不是用 \\n
  • @Thefourthbird 不,它只是检测到空间时的分裂。

标签: java arrays regex arraylist split


【解决方案1】:

您可以在左侧或右侧拆分断言换行符序列\R,或使用替换| 匹配水平空白字符\h

(?=\\R)|(?<=\\R)|\\h

Java demo

例如

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

【讨论】:

    【解决方案2】:

    您只需对\n 使用lookbehind(由?&lt;= 指定)或前瞻(由?= 指定)并与\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]
    

    【讨论】:

      【解决方案3】:
      // 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
      

      【讨论】:

      • 问题是我想要一个包含这个答案的数组,我不想打印 "\n" 感谢@Abra 的答案
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多