如何在Java中查找特定单词之后的特定值?
问题描述:
我从一个BufferedReader
文本,我需要在一个特定的字符串来获得特定的值。如何在Java中查找特定单词之后的特定值?
这是文字:
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 ";"
............
}
}
答
斯普利特的字符串“默认为”,然后使用的indexOf找到的第一次出现“;”。做一个从0到索引的子串,你有你的价值。
见http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
答
如果只关心最终的结果,即得到的东西出你的“=”分隔值的文本文件,你可能会发现内置的Properties对象有帮助吗?
http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html
这确实很多,你需要什么。当然,如果您特意想要手动执行此操作,则可能不是正确的选项。
+0
这应该是答案 – sunil 2012-07-21 17:26:23
答
使用正则表达式:
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);
如果您将文件读入内存(转换为字符串),则可以使用字符串函数。 – thatidiotguy 2012-07-20 15:21:28