簡體   English   中英

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

[英]How to find a specific value after a specific word in Java?

我從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”

像這樣...

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 ";"
      ............
   }
}

如果只關心最終結果,即從“ =”分隔值文本文件中獲取內容,您可能會發現內置的Properties對象有用嗎?

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

這可以滿足您的大部分需求。 當然,如果您特別想手動執行此操作,則可能不是正確的選擇。

分割字符串的“默認值=”,然后使用的indexOf找到的第一次出現“;”。 做一個從0到索引的子字符串,您便擁有了自己的價值。

參見http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

使用正則表達式:

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

您可以使用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);

暫無
暫無

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

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