Introduction:
I was working on formatting wrongly entered numberplates of a car. One business rule was to format all of them in the right perspective. Like 11aa33 should be 11-AA-33. But how to find out where to put the minusses.
The solution
First of all make sure you only have capitals like:
numberplate.toUpperCase();
This takes care of all the characters in the numberplate.
The second step is:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
private static final String MINUS = "-";
private static final String DIGIT_MATCH = "[0-9]{1,3}";
private static final String CHARACTER_MATCH = "[A-Z]{1,3}";
private static final String DIGIT_MATCH = "[0-9]{1,3}";
private static final String CHARACTER_MATCH = "[A-Z]{1,3}";
String formatted = kenteken;
//counting the right amount of minusses.
//counting the right amount of minusses.
if (StringUtils.countMatches(kenteken, MINUS) != 2) {
//the actual patterns to find
Pattern digitPattern = Pattern.compile(DIGIT_MATCH);
Pattern charsPattern = Pattern.compile(CHARACTER_MATCH);
Pattern digitPattern = Pattern.compile(DIGIT_MATCH);
Pattern charsPattern = Pattern.compile(CHARACTER_MATCH);
// find the matches
Matcher digitMatcher = digitPattern.matcher(formatted);
Matcher charsMatcher = charsPattern.matcher(formatted);
Matcher digitMatcher = digitPattern.matcher(formatted);
Matcher charsMatcher = charsPattern.matcher(formatted);
// adding the minusses
if (digitMatcher.find()) {
formatted = new StringBuffer(formatted).insert(
digitMatcher.end(), MINUS).toString();
}
if (charsMatcher.find()) {
formatted = new StringBuffer(formatted).insert(
charsMatcher.end(), MINUS).toString();
}
}
return formatted;
Have fun!
formatted = new StringBuffer(formatted).insert(
digitMatcher.end(), MINUS).toString();
}
if (charsMatcher.find()) {
formatted = new StringBuffer(formatted).insert(
charsMatcher.end(), MINUS).toString();
}
}
return formatted;
Have fun!
Geen opmerkingen:
Een reactie posten