1) Your regex works but is not what I call "easy on the eyes". What about the following:
^[0-9]*$
Your regex works but is not what I call "easy on the eyes". What about the following:
^[0-9]*$
When I read something like this I immediately think: "Some regex with number filters."
2) Also same topic. Do you actually want to allow empty inputs? I would suggest not. Replace *
with +
:
^[0-9]+$
^\\d+$
3) I like static imports. It is not everyones favourite but in my opnion it makes the code more readable. That is why this would be my final solution:
import java.util.Optional;
import static java.util.stream.Collectors.joining;
public class ShoutySnake {
private enum WORDS{ZERO,ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE}
private static final String NUMBERS_ONLY = "^[0-9]+$";
private static String getNumericalCharAsSnakeShoutCaseWord(final int codePoint){
return WORDS.values()[Character.getNumericValue(codePoint)].name();
}
public static String convertNumbersToShoutySnakeCaseWords(final String input) {
return Optional.ofNullable(input)
.filter(s -> s.matches(NUMBERS_ONLY))
.orElseThrow(() -> new IllegalArgumentException("input cannot be null, empty or non-numerical."))
.chars()
.mapToObj(ShoutySnake::getNumericalCharAsSnakeShoutCaseWord)
.collect(joining("_"));
}
}
Also same topic. Do you actually want to allow empty inputs? I would suggest not. Replace
*
with+
:^[0-9]+$ ^\\d+$
I like static imports. It is not everyone's favourite, but in my opinion, it makes the code more readable. That is why this would be my final solution:
import java.util.Optional; import static java.util.stream.Collectors.joining; public class ShoutySnake { private enum WORDS{ZERO,ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE} private static final String NUMBERS_ONLY = "^[0-9]+$"; private static String getNumericalCharAsSnakeShoutCaseWord(final int codePoint){ return WORDS.values()[Character.getNumericValue(codePoint)].name(); } public static String convertNumbersToShoutySnakeCaseWords(final String input) { return Optional.ofNullable(input) .filter(s -> s.matches(NUMBERS_ONLY)) .orElseThrow(() -> new IllegalArgumentException("input cannot be null, empty or non-numerical.")) .chars() .mapToObj(ShoutySnake::getNumericalCharAsSnakeShoutCaseWord) .collect(joining("_")); } }