Groovy — Validating input with a nullable result
Groovy’s full-match operator can validate an entire input token. Parse an accepted token and check its bounds before returning a seat number or null.
A simple example
Turn text into a number
- Start with "2"
- Do this Read an integer, add 1
- Result 3
String text = "2"
if (text.isInteger()) println(text.toInteger() + 1)
3
Validate a seat number
The full-match operator tests the entire token. BigInteger conversion avoids a fixed-width overflow before the range check. A null result represents invalid input.
A minibus has seats numbered 1 to 8. A passenger entering 3 can be assigned that seat. Zero is numeric but outside the seating plan, and x cannot be read as a whole seat number.
Run the example
Groovy 4 on the JVM. Run these commands from the directory containing the example.
groovy Lesson.groovy
Integer seatNumber(String text) {
if (!(text ==~ /[0-9]+/)) return null
def n = text.toBigInteger()
(n in 1..8) ? n.intValue() : null
}
['3', '0', 'x'].each { text ->
def seat = seatNumber(text)
println(seat == null ? 'invalid' : seat)
}
3 invalid invalid
Only whole-number seat labels from 1 through 8 are accepted. The text 3 passes both checks. Zero parses but is outside the range. The letter x does not represent a decimal seat number.
Try it yourself
Predict the results for 8, 9, and an empty string.
Check your answer
Only 8 is accepted. Nine is outside the range and an empty string has no digits. The existing loop can continue after either rejection.