Find valid patterns in each line of a file

Viewed 71

The following is the problem I am trying to solve:

Write a program/script to count and print lines which have the following pattern

Any 4 char sequence which has a pair of two different characters followed by the reverse of that pair e.g xaax or raar. The string is not considered valid if the pattern above exist in square brackets.

Following is a simple approach that is possible:

private static boolean hasValidPattern(String line) {
    for (int i = 0; i < line.length()-3; i++) {
        char first = line.charAt(i);
        char second = line.charAt(i + 1);
        char third = line.charAt(i + 2);
        char fourth = line.charAt(i + 3);
        if (first == fourth && second == third) {
            if (    (i - 1) >= 0
                    && line.charAt(i - 1) == '['
                    && (i + 4) < line.length() &&
                    line.charAt(i + 4) == ']')
                continue;
            else
                return true;
        }
    }
    return false;
}

I was wondering if there is a cleaner way to do this. Probably using regex or something else.

1 Answers

A simple solution with regex will be as follows:

private static boolean hasValidPattern(String line)
{
    return line.matches(".*?(.)(?!\\1)(.)\\2\\1(?:(?!\\])|(?<!\\[.{4})).*");
}

Pattern explanation:

  • .*? - Zero or more characters (as few as possible).

  • (.) - Match one character and capture it in group 1.

  • (?!\\1) - Not followed by the same character.

  • (.) - Match the second character and capture it in group 2.

  • \\2\\1 - Match what was captured in group 2 followed by what was captured in group 1.

  • (?:(?!\])|(?<!\[.{4})) - Assert that the previous 4 characters are not enclosed in square brackets.

  • .* - Zero or more characters (as many as possible; i.e., until the end of the line).

Regex demo - Java demo.

Related