Menu Close

Articles

Java: Regular Expression

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

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.

 

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.

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

See also: oracle documentation