如何获取文本所属的数组

时间:2016-04-19 06:19:42

标签: java arrays regex

我有一个多维数组,如下所示:

dfs={i: g.dropna(axis=1)         
    for i, g in df1.groupby(df1.apply(lambda x: x.notnull().sum() - 2 , axis=1))}

#select DataFrame with len=2    
print dfs[2]
    id channel  p1  p2
1  213    paid  b2  b1

#select DataFrame with len=3       
print dfs[3]
     id channel    p1    p2   p3
2  2222  direct  as25  dw46  32q

如果内部数组包含"酸性暴露(pH)"那么我想创建一个新数组。所以我最终在新数组中只有[[Acid Exposure (pH), Upright], [Recumbent, Total], [, Upright Normal Recumbent Normal Total], [Normal],] [[Bolus Exposure (Impedance)Upright], [, Recumbent, Total], [, Upright Normal Recumbent Normal Total], [Normal]] [[Postprandial Data], [, Postprandial Interval: 120 min]]

我试过了:

[Acid Exposure (pH),  Upright], [Recumbent, Total], [,  Upright Normal Recumbent Normal Total], [Normal],]

但它只是给了我 ArrayList<String> matches = new ArrayList<String>(); Pattern p = Pattern.compile("Acid Exposure \\(pH\\)"); for (List<String> row:twoDim) { for (String cell:row){ if (p.matcher(cell).matches()) { matches.add(cell); System.out.println(matches); } } }

4 个答案:

答案 0 :(得分:1)

您只是检查List中是否有匹配项,并且仅添加此特定项目。你想要设置一个标志并在找到匹配后添加整个List。未经测试,但它应该是这样的:

// Just a hint, define matches a List to be able to change the actuall class of the List more easy.
List<String> matches = new ArrayList<String>();
Pattern p = Pattern.compile("Acid Exposure \\(pH\\)");
for (List<String> row : twoDim) {
    boolean found = false;
    for (String cell : row) {
        if (p.matcher(cell).matches()) {
            System.out.println(matches);
            found = true;
            // Break out of the loop, no need to check for matches anymore
            break;
        }
    }
    if (found) {
        matches.addAll(row);
    }
}

答案 1 :(得分:0)

您只是在代码中打印出匹配的单元格,而您需要的是整行。

为什么不修改'匹配'的类型并将所需的行添加到匹配项中。

答案 2 :(得分:0)

您想要添加整行,但只添加了单元格。

更改

matches.add(cell);

matches.addAll(row)

答案 3 :(得分:0)

int find = 0;

    ArrayList<String> newarray = new ArrayList<>();

    for(int i=0; i < initialArray.size();i++)
    {

        String[][] row = (String[][]) initialArray.get(i);

        for(int k = 0; k < row.length; k++ )
        {
            for(int l=0; l < row[0].length; l++)
            {
                if (row[k][l].equals("Acid Exposure (pH)"))
                {

                    find = i;
                    for(int p =0; p < row[k].length; p++)
                    {
                        newarray.add(row[k][p]);
                    }
                    break;


                }
            }
        }           
    }