Thursday, September 23, 2021

Using Regular Expressions in Java

Using regular expressions in Java can be tricky because the input of the regular expression is a String value. This String value must comply to all the Java syntax tricks before the actual regular expression is applied to the String variable being compared.

For example, I want to ensure that the value passed into my Java method is only a whole number. If it's not, then I can't use this value and must use "0" in my method execution. So, here's the regular expression that I have:

.*[^\d].*/g

. - matches any character except line breaks

* - match 0 or more of the preceding token

[ ] - set

^ - negated

\d - matches any digit character (0-9)

/g - apply expression throughout the entire value being compared

However, in Java I must escape the backslash (and remove the global which is assumed in Java) for this regular expression to work. I end up with:

.*[^\\d].*

An alternate solution could have been the following regular expression without having to worry about escaping any chars in Java's string:

.*[^0-9].*

In the end, I was able to use the following and get the expected results:

boolean hasNonDigit = string.matches(".*[^\\d].*");

if (hasNonDigit) setToZero();


Useful Reference and Online Tools