我试图引入html验证错误并删除错误的第一部分,仅显示实际的文本部分但遇到问题。我想删除" ValidationError第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);
}
}
答案 0 :(得分:1)
简单但不灵活的方法是使用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