Find hidden word with regex


I'm trying to find a hidden word with regex, but I do not understand why my code does not work.

String s = "ahwereovnkejfnlvienfvia";
String regex = "[a-z]h[a-z]o[a-z]l[a-z]a[a-z]";
String regex2 = ".h.o.l.a."
Pattern p = Pattern.compile(regex);

My goal is to know if the string contains the word "hello" hidden in the characters, but it always says no.

The logic I'm trying to use is:

  • any character before or after the characters of the word I'm looking for.
  • I do not know how many characters are in front of or behind each letter of the hidden word.
asked by Roberto Gimenez 12.08.2017 в 16:41

1 answer


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:


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()) {
      Pattern p = Pattern.compile(regex.toString());
      Matcher m = p.matcher(string);
      return m.matches();
answered by 12.08.2017 / 17:10