我从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
这能满足你的需求。当然,如果你特别想手动完成,这可能不是正确的选择。
您可以使用Properties类加载字符串并从中查找任何值
String readString = "aimtolerance = 1024;rn" +
"model = Araarrow;rn" +
"name = Bow and Arrows;rn" +
"range = 450;rn" +
"reloadtime = 3;rn" +
"soundhitclass = arrow;rn" +
"type = Ballistic;rn" +
"waterexplosionclass = small water explosion;rn" +
"weaponvelocity = 750;rn" +
"default = 213;rn" +
"fort = 0.25;rn" +
"factory = 0.25;rn" +
"stalwart = 0.25;rn" +
"mechanical = 0.5;rn" +
"naval = 0.5;rn";
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);
在"default="上拆分字符串,然后使用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);
}