【问题标题】:How to remove text in arraylist element after a specific character?如何在特定字符后删除arraylist元素中的文本?
【发布时间】:2015-01-08 11:29:40
【问题描述】:

我正在尝试引入 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 类的split 方法。

标签: java arraylist


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-07
    • 2011-05-13
    相关资源
    最近更新 更多