Sage-Code Laboratory

Regular Expressions

Regular expressions are a way to describe a set of strings based on common characteristics shared by each string in the set. They can be used to search, edit, or manipulate text and data.

Using Regular Expressions

public class VowelsTest
{
 public static void main(String[] args)
 {
 String s1 = "banana";
 System.out.println(s1 + " has " + Vowels.numberOfVowels(s1) + " vowels");

 String s2 = "Veritas. Virtus. Libertas.";
 System.out.println(s2 + " has " + Vowels.numberOfVowels(s2) + " vowels");

 String s3 = "Veni, vidi, vici";
 System.out.println(s3 + " has " + Vowels.numberOfVowels(s3) + " vowels");
 }
}
public class Vowels
{
	public static int numberOfVowels(String sample)
   {
      String onlyVow = sample.replaceAll("[^AEIOUaeiou]", "");
      //deletes everything that is not what we want
      //replaces it with nothing, effectively deleting it

      return onlyVow.length();
   }
}

The above example consists of a Main method and a public class. The objective here is to count how many vowels there are in each phrase, and print it to the console.

This demonstrate how to use regular expressions.

 

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));
 }
}

See also: oracle documentation


Read next: Switch Expressions