简体   繁体   中英

find the particular string that not being trapped between double quotes java regex

I want to find a string (say x ) that satisfies two conditions:

  1. matches the pattern \\b(x)\\b
  2. does not match the pattern ".*?(x).*?(?<!\\\\)"

In other words, I am looking for a value of x that is a complete word (condition1) and it is not in double quotes (condition2).

  • " x /" m" not acceptable
  • " x \\" " + x + " except" :only the second x is acceptable.

What Java code will find x ?

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 \""
-----------------------^-----------

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM