Skip to content

Instantly share code, notes, and snippets.

@ariesmcrae
Last active April 20, 2018 12:16
Show Gist options
  • Save ariesmcrae/6c7aca46c064d6264ea75ece3c872bb8 to your computer and use it in GitHub Desktop.
Save ariesmcrae/6c7aca46c064d6264ea75ece3c872bb8 to your computer and use it in GitHub Desktop.
Validates the number expected commas in a CSV
/**
* Validate row of csv to see if it has the correct number of commas.
* @param input The csv row to be evaluated.
* @param expectedNumberOfCommas The expected number of commas in the csv row.
*/
public static void validateLine(String input, int expectedNumberOfCommas) {
// Example input: [email protected],Male,21
// Check that there are 2 commas in the input:
// regex = ^([^,]*,){2}[^,]*$
// ^ Start of string
// ( Start of group
// [^,]* Any character except comma, zero or more times
// , A comma
// ){2} End and repeat the group 2 times only. Eg. if we expect only 2 commas for the line.
// [^,]* Any character except comma
// $ End of string
String regex = "^([^,]*,){" + expectedNumberOfCommas + "}[^,]*$";
boolean isCsvValid = Pattern.matches(regex, input);
if (!isCsvValid) {
throw new RuntimeException(
"Invalid csv. Expecting " + expectedNumberOfCommas + " comma(s) per line only.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment