I thought of writing a utility class where I can implement patterns that are useful for day-to-day parsing of strings, without having to to import java.util.regex
everywhere. So I wrote this simple class as a model.
This was inspired by a (now deleted) Stack Overflow question:
For ex: String str="asd14sd67fgh007"; I want the output like: 1467007asdsdfgh
Right now I only added two patterns, with the intention of adding more as the need calls for it. I used regex for these, but other pattern-matching methods could [potentially] also be used, if the need calls for it.
I would be interested to know if there is a smarter way of doing this that I have not thought of, and in general, how can this be improved, to make adding more patterns and methods as easy as possible, keep the code clear and concise, and in general make it better for Mr. or Mrs. Maintainer.
Note: I wrote this using repl.it for the time being, and not actually added to a code base yet, hence the class not being declared as public
. That will be rectified once it's added to a code base.
PatternMatcher
class
import java.util.regex.*;
class PatternMatcher {
public String inputString;
/**
* Constructor.
*/
public PatternMatcher(String inputString) {
this.inputString = inputString;
}
/**
* Get only upper and lower case letters from inputString.
* @return String containing the upper and lower case letters from inputString
*/
public String getLetters() {
final Pattern LETTERS = Pattern.compile("[A-Za-z]");
StringBuilder outputBuilder = new StringBuilder();
Matcher letterMatcher = LETTERS.matcher(inputString);
while (letterMatcher.find()) {
outputBuilder.append(letterMatcher.group());
}
return outputBuilder.toString();
}
/**
* Get only numbers/digits from inputString.
* @return String containing the numbers/digits from inputString
*/
public String getNumbers() {
final Pattern NUMBERS = Pattern.compile("[0-9]");
StringBuilder outputBuilder = new StringBuilder();
Matcher letterMatcher = NUMBERS.matcher(inputString);
while (letterMatcher.find()) {
outputBuilder.append(letterMatcher.group());
}
return outputBuilder.toString();
}
}
Main
class (for testing)
class Main {
public static void main(String[] args) {
String input = "asd14sd67fgh007";
String expectedOutput = "1467007asdsdfgh";
PatternMatcher inputMatcher = new PatternMatcher(input);
StringBuilder actualOutputBuilder = new StringBuilder();
actualOutputBuilder.append(inputMatcher.getNumbers());
actualOutputBuilder.append(inputMatcher.getLetters());
String actualOutput = actualOutputBuilder.toString();
if (actualOutput.equals(expectedOutput)) {
System.out.println("Pattern match succeeded");
} else {
System.out.println("Pattern match failed");
}
}
}