Examples
StringTheory™ provides many ways to work with and manipulate text. Here are some examples to show how our newest features work. Look for more examples soon.
Auto-populate templates with JavaBeans, Hashtables, or ResultSets.
Using the populate() method found in StringTheory, you can use a JavaBean, a Hashtable, or a ResultSet to insert data into any text template that you define. Here is some sample code that does that very thing:
Given a "Customer" bean with the following accessors:
getFirstName()
getLastName()
getAddress1()
getAddress2()
getCity()
getState()
getZip()
getPhone()
getAge()
You can create a template and populate it like so:
------------------------
Customer buyer = FetchCustomerFromOrder(order);
StringTheory template = new StringTheory(
"Name: FirstName LastName\n" +
"Address: Address1 Address2, City, State Zip\n" +
"Ph#: Phone\n" +
"Years old: Age\n");
template.populate( buyer );
------------------------
A call to template.toString() would then produce something like this:
Name: George Bush
Address: 1600 Pennsylvania Ave. (c/o Laura), Washington, DC 20500
Ph#: 202-456-1414
Years old: 57
Describe patterns using a more natural-language syntax.
Say you're trying to create a pattern to validate the format of a credit card like American Express. You could do it using the rx object and a regular expression, like so:
str.rx.matches("^(34|37)\\d{2}-\\d{6}-\\d{5}$");
It's short, sweet, and to the point. But it's unreadable, and unless you are a regular expression wizard, it probably would take more than a few minutes to build. Worse, future programmers that have to deal with your code might not be able to figure out what exactly is going on without considerable effort. Worse, in a few months even you might not know what's what.
StringTheory provides some ready-made regex tools for you in the Built.Text.Lib package that can help make clear what your code is trying to do. So the above regex could be replaced by this:
String amex = ST.STARTS_WITH + "(34" + ST.OR + "37)" +
ST.ANY_DIGIT + ST.REPEAT(2) + "-" +
ST.ANY_DIGIT + ST.REPEAT(6) + "-" +
ST.ANY_DIGIT + ST.REPEAT(5) + ST.END;
str.rx.matches(amex);
Not quite as short and sweet, but the intent of the code is now clearer and it wouldn't take a half hour to safely make a change during code maintenance.
Of course, the Built.Text.Lib package provides some predefined patterns, including some for popular credit cards. So ultimately you could just say:
str.rx.matches(Credit.AMEX);
StringTheory™ and the Scribble Trefoil logo are trademarks of Built Software Corp.
|