Regular Expressions

Literal Strings

3 points

 

Introduction

The first regular expression we'll work with is a String Literal. A String Literal is a sequence of characters, like "at". The regular expression methods match an input string to the String Literal, and the output indicates which matches occurred. For example, if the input string was "cat" there would be a match because "at" occurs inside "cat". If the input string was "sum" there would be no match.

 

Romeo and Juliet

In Shakespeare's Romeo and Juliet, the two warring families are the Montagues and the Capulets. In this program, use a regular expression to calculate how many times each of the terms "Montague" and "Capulet" occurs in the play.

 

Example

Download and run regexExample1.java for an example of how a String Literal works in a regular expression. Feel free to edit "text" and "textSearch" to try out different scenarios as you run the program multiple times.

 

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

 

To Get Started

Use regex1.java as a starting point, and modify it to do the exercise. Some guidance on how to write the program is given in regex1.java. You'll also need to download Romeo and Juliet.

 

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