


One of the most powerful features of the new regex package is the ability to search for and replace Strings and substrings. Chapter 5 provides more complex validation examples. These types of validations are best achieved by using the Matcher and Pattern objects. For example, you might require that a password contain nonalphanumeric characters. The second type of validation requires that the string contain the pattern at some point, but it doesn't require an exact match. For these, the easiest validation method is probably to use the String.matches(String regex), because it rejects anything that doesn't match fully and completely. Generally speaking, there are two types of validation. Again, this in contrast to the String.matches(String regex) method, which requires an exact match. You're doing this because you want explicit access to the Matcher.find method, which allows you to examine the input string and see if any part of it matches the pattern. But the Java code requires explicit usage of the Pattern and Matcher objects, which is slightly more demanding of the programmer.

The pattern used in Listing 1-9 is less complicated than that in Listing 1-8. *\bJava \d(|$), which Table 1-26 dissects. To use the String.matcher(String regex) method, you need to account for any and all characters that might precede or follow the pattern Java \d. Let's explore the pros and cons of each option. You could modify the pattern to allow for characters before and/or after the Java 4 you want to match on, or you could just use the Pattern and Matcher objects.

What happened? Because your input string is I love Java 4, and the Java 4 is preceded by I love, the input isn't an exact match to the pattern Java \d. Fortunately, doing so becomes much easier with regular expressions, as Listing 1-11 (which follows shortly) demonstrates. Regex is a perfect solution for these types of problems.ĭecomposing text: This can also be a challenging activity, particularly if the String in question needs to be split according to complex rules. Of course, this is a little more complex than it sounds, because different names have different lengths, and you don't want to overwrite the next word in your letter when you insert a longer name. Say you want to send a letter to all of your customers, and you want each letter to be personalized by interspersing the customer's name throughout the letter. Search and/or replace: This is another popular usage of regular expressions, and for good reason. In the practical world, people use regular expressions for one of three basic broad categories:ĭata validation: This is the process of making sure that your candidate String conforms to a specific format (e.g., making sure passwords are at least eight characters long and contain at least two digits). In this section, you'll explore slightly more realistic uses of regular expressions.
