how to check if strings is voucher
4 letters separated by (-) then 4 letters separated by (-) then 4 letters separated by (-) 4 letters separated by (-)
ex: ABCD-ABCD-ABCD-ABCD
CodePudding user response:
You could use a regular expression for that, something like this:
void main() {
String voucher = 'ABCD-ABCD-ABCD-ABCD';
RegExp voucherRegex = RegExp(r'^[A-Z]{4}-[A-Z]{4}-[A-Z]{4}-[A-Z]{4}$');
if (voucherRegex.hasMatch(voucher)) {
print('The string is a voucher');
} else {
print('The string is not a voucher');
}
}
this regular expression is only for upper case letters, don't know if can be lower case in your use case
CodePudding user response:
You can use this method to achieve it :
bool isVoucher(String text, [String separator = "-"]) {
final wordsList =
text.split(separator).where((word) => word.length == 4).toList();
return wordsList.length == 4;
}
print(isVoucher("ABCD-ABCD-ABCD-ABCD")); // true
print(isVoucher("ABCD-ABCD-ABCDs")); // false