简体   繁体   English

使用正则表达式拆分字符串数组-Java

[英]Split String Array using Regex - Java

I'm using Java and I have a String array. 我正在使用Java,并且有一个String数组。 I want to split each item of array into smaller elements using Regex (similar to the split method of string but instead of applying split to string I want to apply it to a specific item in an array). 我想使用Regex将数组的每个项目拆分为较小的元素(类似于字符串的split方法,但不是将split应用于字符串,我想将其应用于数组中的特定项目)。 How do I do this? 我该怎么做呢?

For example, suppose I have an array of sentences in an array called "sentences". 例如,假设我在一个称为“句子”的数组中有一个句子数组。 Now I want to split this into a multi dimensional array where the first index would contain an index of sentence and the second index would contain an index of individual words. 现在,我想将其拆分为多维数组,其中第一个索引将包含句子索引,第二个索引将包含单个单词的索引。 In other words, I want to split each sentences using a space. 换句话说,我想使用空格将每个句子分开。

To illustrate, suppose I have a String array with two values - as follows: 为了说明,假设我有一个带有两个值的String数组-如下所示:

sentence[0] = "This is sentence one";
sentence[1] = "This is sentence two";

Now I want to do two things here: 现在我想在这里做两件事:

  1. Create a multi dimensional array where index 1 contains sentence and where index two contains words 创建一个多维数组,其中索引1包含句子,索引2包含单词
  2. To do this I would need to split the sentence array. 为此,我需要拆分句子数组。 How would I do it to create multi dimensional array? 我将如何创建多维数组?
List<String[]> words = new ArrayList<>(sentences.length);
for(String item : sentences)
    words.add(item.split(" "));

Or if you really want to use Arrays only: 或者,如果您真的只想使用数组:

String[][] words = new String[sentences.length][];
for(int i=0;i<sentences.length;i++)
    words[i] = sentences[i].split(" ");
String[][] a = new String[sentences.length][];

for (int i = 0; i < sentence.length; i++) {
    String sentence = sentences[i];
    a[i] = sentence.split(" ");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM