The Power of Matches and Regex

This article will be about using regular expressions (aka regex). I went over some of the basics of using regex in a previous post.

The class bellow creates a method we implement in our main class. Our goal is to determine if there are only Digits in the sample string.

public class OnlyDigits
{
 public static boolean hasOnlyDigits(String sample)
 {
 return sample.matches("-?[0-9]*");
 }
}

Matches is a powerful method that returns either true or false based on the criteria we define in the parentheses. A programmer who knows the rough format of what he can expect can use matches to weed out bad inputs.

Matches can cut out a lot of if/else if blocks of code.

Matches only works on Strings.

Now lets examine the symbols:

[0-9]* – matches any number of digits

-? – checks to see if there is a negative sign in the number, so that we don’t invalidate negative ints.

Here is a list of examples for you to run, and see the results of the Regex

The Main Class

public class OnlyDigitsTest
{
 public static void main(String[] args)
 {
 String s1 = "194t";
 System.out.print(s1 + " is a valid integer? ");
 System.out.println(OnlyDigits.hasOnlyDigits(s1));
 
 String s2 = "ab33103c";
 System.out.print(s2 + " is a valid integer? ");
 System.out.println(OnlyDigits.hasOnlyDigits(s2));
 
 String s3 = "3348yue239";
 System.out.print(s3 + " is a valid integer? ");
 System.out.println(OnlyDigits.hasOnlyDigits(s3));
 
 String s4 = "-46231111";
 System.out.print(s4 + " is a valid integer? ");
 System.out.println(OnlyDigits.hasOnlyDigits(s4));
 
 String s5 = "631";
 System.out.print(s5 + " is a valid integer? ");
 System.out.println(OnlyDigits.hasOnlyDigits(s5));
 }
}