【问题标题】:How to split a String sentence into words using split method in Java? [duplicate]如何使用 Java 中的 split 方法将字符串句子拆分为单词? [复制]
【发布时间】:2018-05-07 08:55:27
【问题描述】:

我需要将一些句子分成单词。

例如:

Upper sentence.
Lower sentence. And some text.

我是这样做的:

String[] words = text.split("(\\s+|[^.]+$)");

但我得到的输出是:

Upper, sentence.Lower, sentence., And, some, text.

应该是这样的:

Upper, sentence., Lower, sentence., And, some, text.

请注意,我需要保留所有字符(.,-?! 等)

【问题讨论】:

  • 这个相对复杂的正则表达式的目的是什么,简单地拆分\\. 应该可以工作。
  • 也许通常的.split("\\W+") 可以。除非您需要处理连字符和撇号等。
  • 也许我没有在我的问题中明确指出,但我需要保留所有字符,即:逗号、句点等。使用 \\W+ 将它们全部删除,我需要像大写、句子这样的输出。 , 下, 句子。, 一些, 文字。
  • 所以要按空格分割??
  • 是的,换行符。我编辑了我的主要帖子。

标签: java regex split


【解决方案1】:

您可以使用以下代码行将字符串拆分为子字符串:

String[] result = speech.split("\\s");

供参考:https://alvinalexander.com/java/edu/pj/pj010006

【讨论】:

    【解决方案2】:

    更新问题的简单答案

        String text = "Upper sentence.\n"+
                "Lower sentence. And some text.";
    

    [just space] 一个或多个 OR 新行一个或多个

        String[] arr1 = text.split("[ ]+|\n+");
        System.out.println(Arrays.toString(arr1));
    

    结果:

     [Upper, sentence., Lower, sentence., And, some, text.]
    

    【讨论】:

    • 我还需要保留所有的字符,所以输出一定要像Upper1, sentence2., Lower3, sentence4., And5, some6, text7, 10。
    • 我更新了答案
    【解决方案3】:

    将点、逗号等替换为空格并将其拆分为空格

    String text = "hello.world this   is.a sentence.";
    String[] list = text.replaceAll("\\.", " " ).split("\\s+");
    System.out.println(new ArrayList<>(Arrays.asList(list)));
    

    结果:[hello, world, this, is, a, sentence]

    编辑:

    如果仅适用于点,则此技巧应该有效...

    String text = "hello.world this   is.a sentence.";
    String[] list = text.replaceAll("\\.", ". " ).split("\\s+");
    System.out.println(new ArrayList<>(Arrays.asList(list)));
    

    [hello., world, this, is., a, sentence.]

    【讨论】:

    • 我还需要保留任何字符,所以我的输出应该是:Upper, sentence., Lower, sentence., And, some, text.
    • 我更新答案
    • 现在可以了。谢谢。
    【解决方案4】:

    在正则表达式中\W+ 匹配一个或多个非单词字符。

    http://www.vogella.com/tutorials/JavaRegularExpressions/article.html

    因此,如果您想获取句子中的单词,可以使用\W+ 作为拆分器。

    String[] words = text.split("\\W+");
    

    这将为您提供以下输出。

    Upper
    sentence
    Lower
    sentence
    And
    some
    text
    

    更新: 由于您更新了问题,如果您想保留所有字符并用空格分隔,请使用\s+ 作为分隔符。

    String[] words = text.split("\\s+");
    

    我检查了以下代码块并确认它也可以使用新行。

    String text = "Upper sentence.\n" +
                "Lower sentence. And some text.";
        String[] words = text.split("\\s+");
        for (String word : words){
            System.out.println(word);
        }
    

    【讨论】:

    • 我还需要保留任何字符,所以我的输出应该是:Upper, sentence., Lower, sentence., And, some, text.
    • 检查更新的答案
    【解决方案5】:

    表达式\\s+ 表示“1 个或多个空白字符”。我认为您需要做的是用\\s* 替换它,这意味着“零个或多个空白字符”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-14
      • 1970-01-01
      • 2020-06-25
      • 2012-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多