Requirement: Parse a String into chunks of numeric characters and alpha characters. Alpha characters should be separated from the numeric, other characters should be ignored.
Example Data:
Input Desired Output 1A [1, A] 12 [12] 12G [12, G] 12ABC-SFS513 [12, ABC, SFS, 513] AGE+W#FE [AGE, W, FE] -12WE- [12, WE] -12- &%3WE- [12, 3, WE]
Question:
The code below accomplishes this. However, I am looking for any suggestions as to a better way to accomplish this (maybe a crazy regex using String.split()
? ) or any changes that could make this code more readable/easy to follow.
Code:
private static String VALID_PATTERN = "[0-9]+|[A-Z]+";
private List<String> parse(String toParse){
List<String> chunks = new LinkedList<String>();
toParse = toParse + "$"; //Added invalid character to force the last chunk to be chopped off
int beginIndex = 0;
int endIndex = 0;
while(endIndex < toParse.length()){
while(toParse.substring(beginIndex, endIndex + 1).matches(VALID_PATTERN)){
endIndex++;
}
if(beginIndex != endIndex){
chunks.add(toParse.substring(beginIndex, endIndex));
} else {
endIndex++;
}
beginIndex = endIndex;
}
return chunks;
}