Regular Expressions

Character Classes

4 points

 

Introduction

A character class defines a group of characters that the regular expression will look for. The characters go inside square brackets []. The characters don't have to be in order. For example, you could base a regular expression on [tsla] and if the input string was "last", that would be a match.

 

Example

Download and run regexExample2.java for an example of how a a Character Class works in a regular expression. Feel free to edit "regex1" and "line" to try out different scenarios as you run the program multiple times.

 

Exercises

1. Set up a regular expression pattern that uses a character class that includes only the letters "adeighmnt ". There is a message hidden in this line:

scrmebpcblklersuzxyvt clpbruxzyzmourwxcpepbljkou zyxwabprsucbxycjtbcll cbmlrsilqrdsbcpnsuvbibplcgxycbzhbrsqt

Use a regular expression to extract the message.

 

2. Consider a regular expression pattern that uses a character class that excludes the digits from 0 to 8, all capital letters, and these lowercase letters: b,c,f,g,j-n,q,uv,x-z. (j-n, for example, includes j, k, l, m and n).

Now, it is difficult to get a regular expression to work with characters that are excluded. So think instead about what should be included. And write a regular expression that implements this. You can include ":" and " " in the list of characters that you'll include.

The message is hidden in these lines:

gM0zflUGtE6DJ1m5hgUcUK4eX2gBfFjHT vTQQlzxPJqpXOMBGz8QaWfIIJz6CsVEIkmzK7sOZkxzw6uvgT5K3MHoNKnI5WTnzrQ81d1uHZ0UIkcQ 2CylRRL4vSiEn0FPlgCMskgkbjLFz:CI WKbnm4bvtxRDZhYy3UUHakkMGUvYbwzfKgWb0pXTHqBAaO4MTjJljIuw6SJGYPzYsknx5LSFl5j9KVAN

Use the regular expression to extract the message.

 

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 regex2.java as a starting point, and modify it to do the exercise.

 

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