What Are 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.

  • ReplaceAll gets rid of everything from the first set of quotes, and replaces it with what is in the second set of quotes. “” means that it is getting replaced with nothing.
  • What exactly did you put inside replaceAll? Why does it help us count the vowels?
    • “[^AEIOUaeiou]” – This is an example of a regular expression(or regex). A regex is a useful tool for recognizing patterns in inputs. Everything that matches the pattern will be replaces in replace all.
      • [] – specifically looks for whatever character is inside the brackets. Putting in [AB] will result in every single A & B being replaced.
      • ^ – is the not operator, it matches to the EXACT OPPOSITE of whats written there.
    • So I’m telling replaceAll to delete everything that isn’t a vowel and making a new word out of it that only consists of vowels.
    • Then we just take the length of the word to get the number of vowels.

This demonstrate how to use regular expressions.

See also: oracle documentation