I was looking at REGEX's as a possible solution for a problem. I made some sample Strings that contained words such as hello, hellllooo, hhhheello, etc. I then created a regex to find all of these types of words. What I not what to do is look at sentence that may or may not contain an inputted word. For example, you type in hellloo, I would like to scan my sentence for words similar to "hellloo" and return 'hello' if found in the sentence. Can I create a regex that is sort of a variable of the user input? If you type in hellloo then I would construct something that returns back similar words to your input from a sentence or file.
Two input strings
String line = "this is hello helloooo hellllooo hhhel hellll what can I do?";
String longLine = "hello man this what can up down where hey my there find now ok stuff jive super sam dude car";
my regex function
public static void regexChecker(String theRegex, String str2Check) {
Pattern checkRegex = Pattern.compile(theRegex);
Matcher regexMatcher = checkRegex.matcher(str2Check);
while(regexMatcher.find()) {
if(regexMatcher.group().length() != 0) {
System.out.println(regexMatcher.group().trim());
}
}
}
running this
regexChecker("\\s[h]*[e]*[l]*[l]*[o]*\\s", line);
returns
hello
hello
hellllooo
hellll
I would like to create a REGEX based off the user input 'helllooo' that returns hello from the second String longLine. Not sure if regex is the right solution, but I would like to know if its possible.
[]? Don't. --- Do you really want the letters to be optional, so it matches e.g. the wordho? Change*to+to require at least one of each letter. --- Replace both\\swith\\bto match word boundaries. --- Regex should be"\\bh+e+l+l+o+\\b". See regex101 for demo.