java - 如何获取文本所属的数组

标签 java arrays regex

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

[[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)”行,我想创建一个新数组,这样我最终只会得到[Acid Exposure (pH),Upright],[Recumbent,Total], [, 直立正常卧式正常总计], [正常],] 在一个新数组中。

我尝试过这个:

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

但它只是给了我[酸暴露(pH)]

最佳答案

您只是检查列表中是否有匹配项,并且仅添加这一特定项目。您宁愿设置一个标志并在找到匹配项后添加整个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);
    }
}

关于java - 如何获取文本所属的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36710072/

相关文章:

java - taskdef java.lang.VerifyError : Bad type on operand stack when TEAM CITY executes build

C 如何访问属于另一个结构中的结构数组一部分的结构的结构成员?

c++ - 是否有用于从另一个不同的 std::array 初始化 std::array 的特定语法?

使用反向引用的 javascript 模式替换不起作用

javascript - 验证时间的正则表达式

java - 通过 JDT API 以编程方式访问 Java 项目的 build.properties

java - Ebean EmbeddedId 映射列到 ManyToOne 关系

javascript - 更改可观察数组会改变自定义绑定(bind)处理程序、knockoutjs 的可见性

python - 正则表达式解析字符串中的百分比

javax.crypto.BadPaddingException : Given final block not properly padded in CipherInputStream