简体   繁体   中英

Extracting value from a string in java

I have a string, and I want to extract the text abcd from this string. I useed the indexOf() method to get the start index, but how we can I set the end index value? The abcd text value is dynamic, so we can't hardcode it like startIndex()+5 . I need some logical code.

String str = "Hi Welcome to stackoverflow : " +"\n"+"Information :"+"\n"+"hostname : abcd"+"\n"+
"questiontype : text"+"value : desc.";

if(str.contains("hostname : "))
{
String value = "hostname : "
int startIndex = str.indexof("hostname : ") + value.length();
// how to find the endIndex() in that case
}

String answer = str.substring( str.indexOf( value) + value.length(), str.indexOf( "questiontype :" ) );

If you want to get the string after "hostname: " you can do:

String str = "Hi Welcome to stackoverflow : " +"\n"+"Information :"+"\n"+"hostname : abcde"+"\n"+
        "questiontype : text"+"value : desc.";
    

int startIndex = str.indexOf("hostname") + "hostname : ".length();
int endIndex = str.indexOf("questiontype") - 1;

String result = str.substring(startIndex, endIndex);

System.out.println(result);

Also note that you can add \n to the text of the string without needing to append it so that: "Hi Welcome to stackoverflow: " +"\n"+"Information..." would work just as fine doing: "Hi Welcome to stackoverflow: \nInformation..."

Perhaps not as efficient as the answers with indexOf, a regex solution is succint.

Optional<String> getValue(String properties, String keyName) {
    Pattern pattern = Pattern.compile("(^|\\R)" + keyName + "\\s*:\\s*(.*)(\\R|$)");
    Matcher m = pattern.matcher(properties);
    return m.find() ? Optional.of(m.group(2)) : Optional.emtpy();
}

String hostname = getValue("...\nhostname : abc\n...", 
                           "hostname").orElse("localhost");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM