The first condition is straight forward. To check second condition you will have to check number of valid double quotes. If they are even then the string captured in first condition is valid.
String text = "basdf + \" asdf \\\" b\" + b + \"wer \\\"\"";
String toCapture = "b";
Pattern pattern1 = Pattern.compile("\\b" + toCapture + "\\b");
Pattern pattern2 = Pattern.compile("(?<!\\\\)\"");
Matcher m1 = pattern1.matcher(text);
Matcher m2;
while(m1.find()){ // if any <toCapture> found (first condition fulfilled)
int start = m1.start();
m2 = pattern2.matcher(text);
int count = 0;
while(m2.find() && m2.start() < start){ // count number of valid double quotes "
count++;
}
if(count % 2 == 0) { // if number of valid quotes is even
char[] tcar = new char[text.length()];
Arrays.fill(tcar, '-');
tcar[start] = '^';
System.out.println(start);
System.out.println(text);
System.out.println(new String(tcar));
}
}
Output :
23
basdf + " asdf \" b" + b + "wer \""
-----------------------^-----------