如何循环遍历数组并从 ArrayList 创建子字符串?

问题描述 投票:0回答:2

我试图通过将错误添加到数组中来解析 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
2个回答
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;

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


0
投票

您可以使用以下循环:

    ArrayList<String> errorFullTexts = new ArrayList<>();
    ArrayList<String> errorMessageTexts = new ArrayList<>();

    //Add the text to the first spot, you can add as many as you would like
    errorFullTexts.add("ValidationError line 23 col 40:'Bad value ius-cors for attribute name on element meta: Keyword ius-cors is not registered.'");

    for(String errorFullText : errorFullTexts){
        errorMessageTexts.add(errorFullText.substring(errorFullText.indexOf(":'")+2, errorFullText.lastIndexOf(".'")));
    }
© www.soinside.com 2019 - 2024. All rights reserved.