[英]How to loop through an array and create substrings from an ArrayList?
我試圖通過將錯誤添加到數組中來解析HTML驗證錯誤,然后遍歷該數組,刪除錯誤的第一部分(例如ValidationError第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));
}
}
使用foreach循環:
List<String> list = new ArrayList<String>();
List<String> msgs = new ArrayList<String>();
for (String s : list) {
msgs.add(s.replaceAll(".*'(.*)'.*", "$1"));
}
list = msgs;
使用正則表達式提取字符串更干凈,並且仍具有足夠的可伸縮性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.