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.