【问题标题】:How to loop through an array and create substrings from an ArrayList?如何遍历数组并从 ArrayList 创建子字符串?
【发布时间】:2015-01-17 15:45:39
【问题描述】:

我试图通过将错误添加到数组来解析 HTML 验证错误,然后遍历数组,去掉错误的第一部分(例如 ValidationError line 23 col 40:),然后我只想将文本保留在单引号内并将其保存到新列表中。

这是我的工作,但我知道它不可扩展,仅适用于 String fullText 而不是 ArrayList 列表,所以这就是我需要帮助的地方。谢谢!

package htmlvalidator;

import java.util.ArrayList;

public class ErrorCleanup {

public static void main(String[] args) {
    //Saving the raw errors to an array list
    ArrayList<String> list = new ArrayList<String>();

    //Add the text to the first spot
    list.add("ValidationError line 23 col 40:'Bad value ius-cors for attribute name on element meta: Keyword ius-cors is not registered.'");

    //Show what is in the list
    System.out.println("The full error message is: " + list);       

    String fullText = "ValidationError line 23 col 40:'Bad value ius-cors for attribute name on element meta: Keyword ius-cors is not registered.'";

    //Show just the actual message
    System.out.println("The actual error message is: " + fullText.substring(fullText.indexOf("'") + 1));


}

}

【问题讨论】:

    标签: java arrays loops arraylist substring


    【解决方案1】:

    使用 foreach 循环:

    List<String> list = new ArrayList<String>();
    List<String> msgs = new ArrayList<String>();
    for (String s : list) {
        msgs.add(s.replaceAll(".*'(.*)'.*", "$1"));
    }
    list = msgs;
    

    使用正则表达式提取字符串更简洁,并且仍然具有足够的可扩展性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-24
      • 2017-04-28
      • 1970-01-01
      • 2016-06-01
      • 2015-09-11
      • 1970-01-01
      • 2012-10-14
      相关资源
      最近更新 更多