如何在Java中的特定单词后找到特定值?

时间:2012-07-20 15:18:56

标签: java string find bufferedstream

我从BufferedReader获得了一个文本,我需要在特定字符串中获取特定值。

这是文字:

    aimtolerance = 1024;
    model = Araarrow;
    name = Bow and Arrows;
    range = 450;
    reloadtime = 3;
    soundhitclass = arrow;
    type = Ballistic;
    waterexplosionclass = small water explosion;
    weaponvelocity = 750;

        default = 213;
        fort = 0.25;
        factory = 0.25;
        stalwart = 0.25;
        mechanical = 0.5;
        naval = 0.5;

我需要得到两者之间的确切数字 默认= ;

哪个是“213”

5 个答案:

答案 0 :(得分:3)

像这样......

String line;
while ((line = reader.readLine())!=null) {
   int ind = line.indexOf("default =");
   if (ind >= 0) {
      String yourValue = line.substring(ind+"default =".length(), line.length()-1).trim(); // -1 to remove de ";"
      ............
   }
}

答案 1 :(得分:0)

如果只关心最终结果,即从'='分隔值文本文件中获取内容,您可能会发现内置的Properties对象有用吗?

http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html

这可以满足您的需求。当然,如果您特别想手动执行此操作,则可能不是正确的选择。

答案 2 :(得分:-1)

将字符串拆分为“default =”,然后使用indexOf查找第一次出现的“;”。从0到索引的子字符串,你有你的价值。

请参阅http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

答案 3 :(得分:-1)

使用正则表达式:

private static final Pattern DEFAULT_VALUE_PATTERN
        = Pattern.compile("default = (.*?);");

private String extractDefaultValueFrom(String text) {
    Matcher matcher = DEFAULT_VALUE_PATTERN.matcher(text);
    if (!matcher.find()) {
        throw new RuntimeException("Failed to find default value in text");
    }
    return matcher.group(1);
}

答案 4 :(得分:-1)

您可以使用Properties类加载字符串并从中查找任何值

String readString = "aimtolerance = 1024;\r\n" + 
"model = Araarrow;\r\n" + 
"name = Bow and Arrows;\r\n" + 
"range = 450;\r\n" + 
"reloadtime = 3;\r\n" + 
"soundhitclass = arrow;\r\n" + 
"type = Ballistic;\r\n" + 
"waterexplosionclass = small water explosion;\r\n" + 
"weaponvelocity = 750;\r\n" + 
"default = 213;\r\n" + 
"fort = 0.25;\r\n" + 
"factory = 0.25;\r\n" + 
"stalwart = 0.25;\r\n" + 
"mechanical = 0.5;\r\n" + 
"naval = 0.5;\r\n";
readString = readString.replaceAll(";", "");
Properties properties = new Properties();

System.out.println(properties);
try {
    properties.load(new StringReader(readString));
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
System.out.println(properties);

String requiredPropertyValue = properties.getProperty("default");
System.out.println("requiredPropertyValue : "+requiredPropertyValue);