Home > Blockchain >  Getting substring of a string that has a repeating character Java
Getting substring of a string that has a repeating character Java

Time:06-21

I'm a writing a parser that will extract the tag and value out of a line that it reads from a file and I want to know how to get the value. So in this case I want to get key = "accountName" and value = "fname LName" and have it repeat with each line.

<accountName>fname LName</accountName>
<accountNumber>12345678912</accountNumber>
<accountOpenedDate>20200218</accountOpenedDate>

This is my code, this is within a while loop that is scanning each line using bufferedReader. I managed to get the key properly, but when I try to get the value, I get "String index out of range - 12. Not sure how to get the value between the two arrows > <.

String line;
if(line.startsWith("<"){
    key = line.substring(line.indexOf("<" 1, line.indexOf(">"));
    value = line.substring(line.indexOf(">" 1, line.indexOf("<") 1);
}

CodePudding user response:

Though it is recommended to use XML parser but still if you want to do it by manually processing the string at each line: (using regular expression is recommended to process line) but if you want todo manually with substring way here is the example:

private static void readKeyValue(String line) {
    String key = null;
    String value = null;
    if (null != line && line.startsWith("<") && line.contains("</")) {
        key = line.substring(line.indexOf("</")  2 , line.lastIndexOf(">"));
        value = line.substring(line.indexOf(">")   1, line.indexOf("</"));
    }
    System.out.println("key: "  key);
    System.out.println("value: "  value);
}

CodePudding user response:

You can use regular expressions to extract, assuming the line variable is a string read from each line.

    String pattern = "<([a-zA-Z] .*?)>([\\s\\S]*?)</[a-zA-Z]*?>";
    // Create a Pattern object
    Pattern r = Pattern.compile(pattern);
    // Now create matcher object.
    Matcher m = r.matcher(line);
    // find
    if (m.find()) {
        String key = m.group(1);
        String value = m.group(2);
        System.out.println("Key: "   key);
        System.out.println("Value: "   value);
    } else {
        System.out.println("Invalid");
    }
  • Related