samedi 25 juin 2016

Java Reg Exp for Word not followed by another word

Basically, I am writing a program in java where I have to categorize a String in any of three buckets.

  • Category 1 - String with both 'AND' and 'AND NOT'
  • Category 2 - String with 'AND NOT'
  • Category 3 - String with 'AND'

I need some regex to match string having AND followed by NOT if not skip.

A AND B AND NOT C - Fail
A AND B AND C - Fail
A AND NOT B AND NOT C - Pass

Below is sample code snippet

public static void main(String[] args) {
    String X = "A AND B AND C AND D AND NOT E";
    String Y = "A AND NOT C ";
    String Z = "A AND B AND D";
    ArrayList<String> sampleString=new ArrayList<String>(Arrays.asList(X,Y,Z));

    //Category 1 - String with both 'AND' and 'AND NOT'
    //Category 2 - String with 'AND NOT' only
    //Category 3 - String with 'AND' only

    for(String s:sampleString){
        if(s.contains("AND") && s.contains("NOT")){
            System.out.println("Category 1 -"+s);
        }
        // This condition is invalid - I need some regex to match this condition. I need to consider only AND followed by NOT if not skip

        if(s.contains("AND NOT") && !s.contains("AND")){
            System.out.println("Category 2 - "+s);
        }
        if(s.contains("AND") && !s.contains("NOT")){
            System.out.println("Category 3 - "+s);
        }
    }

OUTPUT -

Category 1 -A AND B AND C AND D AND NOT E
Category 1 -A AND NOT C 
Category 3 - A AND B AND D

I tried some regex questions but doesn't resolve mine. I tried with below

String regex="AND(?!\\s+NOT)";

public static void main(String args[]){
        String x= "A AND B AND C AND NOT D"; 
        String regex="AND(?!\\s+NOT)";
        if(Pattern.compile(regex).matcher(x).find()){
            System.out.println("X MATCHED");
        }
    } 
//Returns - X MATCHED

Any help would be much appreciated!

Aucun commentaire:

Enregistrer un commentaire