laurakellie
laurakellie

Reputation: 47

How to remove text in arraylist element after a specific character?

I am trying to pull in html validation errors and strip out the first part of the error to only show the actual text part but am having trouble. I would like to remove the "ValidationError line 23 col 40:' " and the last " ' " after the text.

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);

}

}

Upvotes: 2

Views: 270

Answers (1)

nem035
nem035

Reputation: 35491

Simple but inflexible way would be to use the String.substring() method

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

If you know your message will always be between single quotes, you could make a helper method to extract it like:

// 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
}

And then use it like:

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

Another way could be to use a regular expression.

Here is a good SO thread about using regex to get substrings between single quotes

Upvotes: 1

Related Questions