Reputation: 925
I've got around 10 lines of data in a text file below containing the following
X-Value = -0.525108, Y-Value = 7.746691, Z-Value = 5.863008, Timestamp(milliseconds) = 23001
X-Value = -0.755030, Y-Value = 7.861651, Z-Value = 6.016289, Timestamp(milliseconds) = 23208
The code I have right now uses a BufferedReader reading every line of the file but what I really want to do is extract the X-Value, Y-Value, Z-Value and Timestamp(milliseconds) values from each line. Could this be done with using simple String methods such as substring or would this suit the use of regular expressions?
Upvotes: 1
Views: 156
Reputation:
Why play around with split(), just go for a regex!
X-Value\s*=\s*([\d.+-]*).*Y-Value([\d.+-]*).*Z-Value\s*=\s*([\d.+-]*).*Timestamp\(milliseconds\)\s*=\s*(\d*)
Upvotes: 0
Reputation: 759
String s = "X-Value = -0.525108, Y-Value = 7.746691, Z-Value = 5.863008, Timestamp(milliseconds) = 23001";
s = s.replaceAll(" ", "");
String[] split = s.split("=|,");
BigDecimal x = new BigDecimal(split[1]);
BigDecimal y = new BigDecimal(split[3]);
BigDecimal z = new BigDecimal(split[5]);
String ts = split[7];
Upvotes: 0
Reputation: 785058
You can use scanner like this to extract your values:
String str = "X-Value = -0.525108, Y-Value = 7.746691, Z-Value = 5.863008, Timestamp(milliseconds) = 23001";
Scanner scanner = new Scanner(str);
if (scanner.findInLine("^X-Value\\s*=\\s*([^,]*),\\s*Y-Value\\s*=\\s*([^,]*),\\s*Z-Value\\s*=\\s*([^,]*),\\s*Timestamp\\(milliseconds\\)\\s+=\\s+([^,]*)\\s*$") != null) {
MatchResult result = scanner.match();
System.out.printf("x=[%s]; y=[%s]; z=[%s]; ts=[%s]%n", result.group(1), result.group(2), result.group(3), result.group(4));
}
scanner.close();
OUTPUT:
x=[-0.525108]; y=[7.746691]; z=[5.863008]; ts=[23001]
Upvotes: 1
Reputation: 49547
You can use String.split
to split your string on ,
and =
String str = "X-Value = -0.525108, Y-Value = 7.746691, Z-Value = 5.863008, Timestamp(milliseconds) = 23001";
ArrayList<String> final_data = new ArrayList<String>();
String[] data = str.split(",");
for(String S : data)
final_data.add(S.trim().split("=")[1]);
for(String s : final_data)
System.out.println(s.trim());
Output =
-0.525108
7.746691
5.863008
23001
Upvotes: 2
Reputation: 13356
You can first split the strings by ,
s, then split each part by =
, then trim leading/trailing spaces as necessary.
You can use String.split()
or java.util.StringTokenizer
for this.
Upvotes: 4