gpt4 book ai didi

java - 如何在特定字符后删除 arraylist 元素中的文本?

转载 作者:行者123 更新时间:2023-11-30 11:12:30 25 4
gpt4 key购买 nike

我试图引入 html 验证错误并删除错误的第一部分以仅显示实际的文本部分,但我遇到了麻烦。我想删除“ValidationError line 23 col 40:'”和文本后的最后一个“'”。

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 error message is: " + list);

}

}

最佳答案

简单但不灵活的方法是使用 String.substring()方法

String fullText = list.get(0);                              // get the full text  
String msg = fullText.substring(32, fullText.length() - 1); // extract the substring you need
System.out.println("The error message is: " + msg); // print the msg

如果你知道你的消息总是在单引号之间,你可以创建一个辅助方法来提取它:

// get first occurrence of a substring between single quotes
String getErrorMsg(String text) {
StringBuilder msg = new StringBuilder();
int index = 0;
boolean matchingQuotes = false; // flag to make sure we matched the quotes
while(index < text.length()) {
if(text.charAt(index) == '\'') { // find the first single quote
index++; // skip the first single quote
break;
}
index++;
}
while(index < text.length()) {
if(text.charAt(index) == '\'') { // find the second single quote
matchingQuotes = true; // set the flag to indicate the quotes were matched
break;
} else {
msg.append(text.charAt(index));
}
index++;
}
if(matchingQuotes) { // if quotes were matched, return substring between them
return msg.toString();
}
return ""; // if reached this point, no valid substring between single quotes
}

然后像这样使用它:

String fullText = list.get(0);                      // get the full text  
String msg = getErrorMsg(fullText); // extract the substring between single quotes
System.out.println("The error message is: " + msg); // print the msg

另一种方法是使用正则表达式。

这是一个good SO thread about using regex to get substrings between single quotes

关于java - 如何在特定字符后删除 arraylist 元素中的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26872975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com