Regular expressions, regexp for short, allow us to build expressions for pattern matching. If you aren’t familiar with them you may want to check out some resources here.
In Java you can leverage the power of regexp using the pattern and matcher classes, you can import java.util.regex.* to make them available to your program. Let’s see some examples:
|
1 2 3 |
public static boolean basicRegexp(String pattern, String str) { return Pattern.matches(pattern, str); } |
This is a simple method that takes in a pattern and a string to compare against and returns either true or false. We define patterns as strings, for example if we want to see if a word starts with any character but ends with “ello” we would call our method like this:
|
1 |
boolean result = basicRegexp(".ello","hello"); |
Which in this case will return true, as an alternative you could also use the String method startsWith()
Now lets say we want to find all words that match a certain pattern in a piece of text, rather than just comparing against a single word.
|
1 2 3 4 5 6 7 8 |
private static void findWithPattern(String regexp, String str) { Pattern pattern = Pattern.compile(regexp); Matcher matcher = pattern.matcher(str); while (matcher.find()) { System.out.println(matcher.group()); } } |
This method is a little more involved than the first one. First we need to compile our regexp and get a pattern object then we call the matcher method on our pattern object with the string we want to match against, and what we get is a matcher object which contains the results. Finally we loop over the results and print them to the screen.
Here is a possible call to our findWithPattern method.
|
1 |
findWithPattern("h\w+","hello halo hulo"); |
For more details check the official documentation.