Logical operators in regular expressions in java

We have already seen the Or operator in previous post

  System.out.println("Harry".replaceAll("[Hh]arry", "Tommy"));

i.e replace Harry or harry with Tommy

And for AND operator we have "abc" i.e a followed by b followed by c

We also know that if we put carrot character in square brackets it becomes a not operator [^]

Lets see an example of it below

      String tvTest = "tstvtkt";
     String tNotVRegExp = "t[^v]"; //find all t that are  not followed by v
    //Please note using the above method the last t will never get printed as [^v] is actually looking for an element i.e any element other than v but 
     atleast some element .but last t is not followed by any element so it will not be added.
     Pattern tNotVPattern = Pattern.compile(tNotVRegExp);
     Matcher tNotVMatcher = tNotVPattern.matcher(tvTest);
     counter = 0;
        while (tNotVMatcher.find()){
            counter++;
            System.out.println("Occurences "+counter +" : "+tNotVMatcher.start()+" to "+tNotVMatcher.end());
        }

Please note that as discussed in above code the reg expression will only print all t that are not followed by v

It will not print the last t i.e t not followed by anything. the reason for that is the reg expression has to be a exact match i.e t followed by something that is not v

The reason is carrot character ^ inside square braces [] always look for some character.

To solve this we use the not operator i.e t not followed by v but can be also not followed by anything else example

The below is a negative look ahead expression i.e a t then ? and negative v i.e either something other than v or nothing at all as we have put ? there.

 String tNotVRegExp = "t(?!v)";

If we only want all t followed by v we use equal sign

 String tNotVRegExp = "t(?=v)";