Validate co-ordinates as doubles:
See context and testbench below:
public static void main(String[] args) throws IOException {
String input = "51.057,6.76;51.059,6.759;51.062,6.76;51.063,6.76;51.064,6.76;51.067,6.761;"
+ "51.07,6.762;51.072,6.763;51.074,6.765;51.076,6.767;51.077,6.769;51.078,6.772;"
+ "51.079,6.776;51.079,6.776;51.079,6.776;51.08,6.78;51.08,6.78;51.081,6.782;51.082,6.783;"
+ "A,4.0;BB,53.1";
List<String> coordinates = Arrays.asList(input.split(";"));
Pattern splitByCommaPattern = Pattern.compile(",");// Always pre-compile regex before loop
// Validate that co-ordinates are doubles and store in list as Double
List<Map<String, Double>> result = new ArrayList<>();
for (String xyAsString : coordinates) {
String[] xySplit = splitByCommaPattern.split(xyAsString);
String xAsString = xySplit[0];
String yAsString = xySplit[1];
addXYtoResult(xAsString, yAsString, result);
}
System.out.println("\nPrint result:");
result.forEach(xyMap -> System.out.printf("X = '%s' and Y = '%s' %n", xyMap.get("x"), xyMap.get("y")));
}
private static void addXYtoResult(String xAsString, String yAsString, List<Map<String, Double>> result) {
try {
Map<String, Double> xyMap = new HashMap<>();
xyMap.put("x", Double.parseDouble(xAsString));
xyMap.put("y", Double.parseDouble(yAsString));
result.add(xyMap);
} catch (NumberFormatException nfe) {
System.out.printf("This co-ordinate does not have "
+ "valid number format and cannot be parsed "
+ "to doubles: '%s,%s'.%n", xAsString, yAsString);
}
}
Output:
This co-ordinate does not have valid number format and cannot be parsed to doubles: 'A,4.0'.
This co-ordinate does not have valid number format and cannot be parsed to doubles: 'BB,53.1'.
Print result:
X = '51.057' and Y = '6.76'
X = '51.059' and Y = '6.759'
X = '51.062' and Y = '6.76'
X = '51.063' and Y = '6.76'
X = '51.064' and Y = '6.76'
X = '51.067' and Y = '6.761'
X = '51.07' and Y = '6.762'
X = '51.072' and Y = '6.763'
X = '51.074' and Y = '6.765'
X = '51.076' and Y = '6.767'
X = '51.077' and Y = '6.769'
X = '51.078' and Y = '6.772'
X = '51.079' and Y = '6.776'
X = '51.079' and Y = '6.776'
X = '51.079' and Y = '6.776'
X = '51.08' and Y = '6.78'
X = '51.08' and Y = '6.78'
X = '51.081' and Y = '6.782'
X = '51.082' and Y = '6.783'
want to write Regular Expression to validate the same
- What do you want to validate?