Ask Questions?

View Latest Questions

Advertisement


 
 

Regex Exercises 2
Posted on: July 26, 2006 at 12:00 AM
Regular expressions do not have to be written as Java strings (eg, no Java string escape for the '\').

Java: Regex Exercises 2

This is another example of regular expression.

 

In this example we are using Pattern class to compile the regular expression string.

 

Then using the matcher method on the patterns class to get the found data.

 

 

Name _______________________________

 

Assume

Example is below:

 


String subject = . . .
String regex;
String result;
. . .
Pattern pat = Pattern.compile(regex);
Matcher mat = pat.matcher(subject);
while (mat.find()) {
    System.out.println(mat.group());
}

Answer the following questions. Regular expressions do not have to be written as Java strings (eg, no Java string escape for the '\').

  1. Regex that matches the letter 'x'.
    Regex: ___________________________________
  2. Regex that matches any character followed by 'x'.
    Regex: ___________________________________
  3. Regex that matches words, where a word is a series of ASCII alphabetic characters. Match both upper- and lowercase.
    Regex: ___________________________________
  4. Regex that matches a series of vowels (a, e, i, o, or u). Match both upper- and lowercase.
    Regex: ___________________________________
  5. Any four-letter sequence. The word may be embedded in another word. For example, matching on "This is a terrible test" would match "This", "terr", "ible", and "test". Match both upper- and lowercase.
    Regex: ___________________________________
  6. Any four-letter word, but do not allow them to be embedded in another word. For example, matching on "This is a terrible test" would match "This"and "test". Match both upper- and lowercase.
    Regex: ___________________________________
  7. You want to scan a Java source program and print all the subscripts that follow the variable a. The subscript text between the square brackets should be put into group 1. For subject "xa[1] = a[2] + a[3];", group 1 will be "2" on the first match, and "3" on the second. You will have to be very careful with escaping some regular expression characters, because [ and ] have special meanings in regular expressions.
    Regex: ___________________________________
Copyleft 2004 Fred Swartz MIT License
Advertisement


DMCA.com