The regular expression that you have defined is not suitable for the problem you are trying to solve because:
- allows the existence of a single character before each letter of the word
"hola"
- characters between words are not optional
Only matchearia strings that meet these conditions, such as 1h2o3l4a5
What you need is a regular expression that allows 0 or more characters between the letters and that you can achieve with .*
.*
is analogous to using .{0,}
, and represents any character, 0 or more times .
The regular expression to use would be:
.*h.*o.*l.*a.*
In Java you can define a method that receives a string to be checked and a hidden word to be found and based on the latter build the regular expression:
public static void main(String[] args) {
System.out.println(findWord("h_o_l4a$#", "hola")); // true
System.out.println(findWord("1$h#2o3#l4#a5", "hola")); // true
System.out.println(findWord("1h2o3l4a5","hola")); // true
System.out.println(findWord("ha2loa","hola")); // false
System.out.println(findWord("#a$di0os", "adios")); // true
System.out.println(findWord("ad?i0os1", "adios")); // true
System.out.println(findWord("1ad1os?","adios")); // false
}
private static boolean findWord(String string, String hiddenWord){
StringBuilder regex= new StringBuilder(".*");
for (char c: hiddenWord.toCharArray()) {
regex.append(c);
regex.append(".*");
}
Pattern p = Pattern.compile(regex.toString());
Matcher m = p.matcher(string);
return m.matches();
}