Regular Expressions

Matching Digits

4 points

 

Introduction

In regular expressions, to match a digit, you set 'regex' equal to "\\d". To match the end of a word, use "\\b". To match more than 1 digit, add {}. For example, to match 2 adjacent digits, use "\\d{2}". (In the video linked to below, the use of brackets is discussed at 9:30.)

Credit cards come in various formats. They can have 16 digits or more than 16 digits. Also, American Express cards start with 3, Visa cards start with 4, MasterCards start with 5, and Discover cards start with 6. If you look at the input file (creditCards.txt), you'll see that the card numbers have 16, 17 or 18 digits. Most of them start with 3, 4, 5 or 6, but some start with 7. In this program, the user specifies which company's credit cards it wants to see. The program uses a regular expression to find cards with exactly 16 digits, and the hyphens, and it prints the card numbers issued by that company. The regular expression should end with \\b to indicate that there are no additional digits after the last 4. See the output file (creditCardOutput.txt) to see how the program runs once it's complete.

 

Regexr: Feel free to experiment with any of these regular expressions ideas at https://regexr.com, which is also linked below.

 

To Get Started

Download creditCards.txt, the input file. Also have a look at creditCardOutput.txt, which shows the output from a complete program. Finally, download regex5.java, which is the program that you'll modify.

 

Resources

Regexr website
https://regexr.com

 

Video:
https://www.youtube.com/watch?v=rhzKDrUiJVk

 

Regular Expressions tutorial (Oracle)
https://docs.oracle.com/javase/tutorial/essential/regex/

 

Pattern class in Java API:
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/regex/Pattern.html

 

Matcher class in Java API:
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/regex/Matcher.html