Simple wildcard searches for pattern matching

For a search test I was working on, I needed to verify what was returned for the name of a warehouse location. Normally the .contains command would be used, but for this test, I needed to check for multiple criteria. I need to check the warehouse is assigned to a certain coast and contains certain city values. The warehouse could be East or West with several city names listed afterward in any given order. For example, the warehouse location could look like:

String branchName="Warehouse East #585 Palm Beach, FL Charlottesville, VA Nampa, ID Charlottesville, VA"
String branchName="Warehouse West Los Angeles, CA, San Francisco, CA, San Diego, CA"

I want to verify "Warehouse East" is part of the text and I want to verify "Palm Beach" is in the text. Since these two strings are not next to each other and the city could appear anywhere on the line the .contains will not work in this instance.

However, the .matches command can be used which supports the wildcards, * and ?. The usage is the same as we see for filenames. For example *image* matches all filenames with the word image such as image, images, fileimage. The only difference is we have to "escape" the wildcard with the use of .*

With that in mind we can make the following command verify our chosen text strings exist in the returned result.

println(branchName.matches("Warehouse East .*Palm Beach.*"))

To use the single wildcard .? we could write the line as:

println(branchName.matches(".?arehouse .?ast .*Palm Beach.*"))

This ignores the case for the W and E, so Warehouse East is the same as warehouse east

It is also possible to use a more "regex" style and write the above line as:

println(branchName ==~/.?arehouse .?ast .*Plam Beach.*/)

This falls into the brute force category of pattern matching, but I have pretty simple needs and taking the time to write a custom parser isn't necessary and ins't in the cards.

If you’ve come as an elf, see it through as an elf.

Author Signature for Posts

0