簡體   English   中英

從 java 中的字符串中提取值

[英]Extracting value from a string in java

我有一個字符串,我想從這個字符串中提取文本abcd 我使用indexOf()方法來獲取起始索引,但是我們如何設置結束索引值呢? abcd文本值是動態的,所以我們不能像startIndex()+5那樣對其進行硬編碼。 我需要一些邏輯代碼。

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

如果您想在"hostname: "之后獲取字符串,您可以執行以下操作:

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

另請注意,您可以將\n添加到字符串的文本中,而無需 append ,這樣: "Hi Welcome to stackoverflow: " +"\n"+"Information..."可以正常工作: "Hi Welcome to stackoverflow: \nInformation..."

也許沒有 indexOf 的答案那么有效,正則表達式解決方案很簡潔。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM