Java Reference
In-Depth Information
Let's look at an example of the various metacharacters. Suppose we have the following
Pattern :
14. String regex = “.ing”;
15. Pattern pattern = Pattern.compile(regex);
The dot in a regular expression represents any character, so ”.ing” says “match any
word that begins with any character and ends in ing.” Using this pattern, see if you can
determine the output of the following statements:
16. String [] tests = {“ing”, “ring”, “trying”, “running”, “beings”};
17. for(String test: tests) {
18. Matcher m = pattern.matcher(test);
19. if(m.matches()) {
20. System.out.println(test + “ matches “ + regex);
21. }
22. }
The for loop on line 17 iterates through the tests array and creates a Matcher object
for each String in the array. Line 19 invokes the matches method in Matcher , which
returns true if the pattern matches the String . The only String in tests that consists of
one character and ends in ”ing” is ”ring” , so the output of the code is
ring matches .ing
If you want to match all words that end in ”ing” , then use the * metacharacter, which
matches the preceding character any number of times. Assuming we use the same tests
array from earlier, see if you can determine the matches of the following pattern:
String regex = “.*ing”;
Pattern pattern = Pattern.compile(regex);
The regular expression ”.*ing” matches any word ending in ”ing” , so the matches from
the tests array are
ing matches .*ing
ring matches .*ing
trying matches .*ing
running matches .*ing
Use square brackets ( [] ) to denote a list or range of specifi c characters in a regular
expression. For example, the pattern [aeiou] matches any vowel. Use a hyphen ( - ) to spec-
ify a range of characters. For example, the expression [q-v] is equivalent to [qrstuv] . The
pattern [a-zA-Z] matches any uppercase or lowercase letter of the alphabet. See if you can
determine the types of strings that match the following pattern:
String regex = “[qrstuv]*.ing”;
Pattern pattern = Pattern.compile(regex);
Search WWH ::




Custom Search