I got a text from a BufferedReader
and I need to get a specific value in a specific string.
This is the text:
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;
I need to get the exact number between
default = and ;
Which is "213"
Something like this....
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 ";"
............
}
}
If just care about the end result, i.e. getting stuff out of your '=' separated values text file, you might find the built in Properties object helpful?
http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html
This does much of what you need. Of course if you're specifically wanting to do this manually, it's maybe not the right option.
you can use Properties class to load the string and find any value from it
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);
Split the string on "default =" and then use indexOf to find the first occurrence of ";". Do a substring from 0 to the index and you have your value.
See http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
Using regular expressions:
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);
}