在java中从字符串中提取值

在java中从字符串中提取值,java,Java,我有一个字符串,我想从这个字符串中提取文本。我使用了indexOf()方法来获取开始索引,但是如何设置结束索引值呢?文本值是动态的,所以我们不能像startIndex()+5那样硬编码。我需要一些逻辑代码 String str = "Hi Welcome to stackoverflow : " +"\n"+"Information :"+"\n"+"hostname : abcd"+"

我有一个字符串,我想从这个字符串中提取文本。我使用了
indexOf()
方法来获取开始索引,但是如何设置结束索引值呢?文本值是动态的,所以我们不能像
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 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
添加到字符串的文本中,而无需附加它,这样:
“Hi Welcome to stackoverflow:”+“\n”+“Information…”
也可以很好地工作:
“Hi Welcome to stackoverflow:\n信息…”
可能没有使用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");
可选的getValue(字符串属性、字符串键名){
Pattern=Pattern.compile(“(^ |\\R)”+keyName+“\\s*:\\s*(.*)(\\R |$)”;
Matcher m=模式匹配器(属性);
返回m.find()?可选的(m.group(2)):可选的.emtpy();
}
字符串hostname=getValue(“…\n主机名:abc\n…”),
“主机名”).orElse(“本地主机”);

这些可能很有用:,。您可以查找abcd值之后的内容,并使用此信息获取结束索引。如何查找结束索引?问题是答案:这取决于文本结尾的定义。除非您指定文本符合的结构,否则您无法真正知道剩余值的长度。似乎在每个值后面都有一个换行符,因此您可以使用
str.substring(startIndex,str.indexOf(“\n”,startIndex))
在键后面搜索换行符。
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");