-2

I am new to Java.I am looking for a regular expression which will tell if the given string has "AND" placed at proper positions, that is, it is a valid AND operation. Eg :

  1. How AND why : VALID
  2. Try AND succeed AND pass : VALID
  3. Try succeed AND : INVALID ( since AND is at last index )
  4. Try AND AND succeed AND pass : INVALID ( since there are 2 consecutive ANDs )
ishita07
  • 37
  • 7
  • Hi, could you please post your code as well? – mettleap Jun 24 '20 at 16:30
  • Hi @mettleap : I was not able to write code for reg ex for this hence posted this question :) – ishita07 Jun 24 '20 at 16:37
  • This site is good for creating regexs https://regexr.com/ – Atahan Atay Jun 24 '20 at 16:40
  • @AtahanAtay - regarding regexr.com: yes, but not necessarily for Java regexes. It supports "_JavaScript & PHP/PCRE RegEx_". See also [this](https://stackoverflow.com/questions/14030146/what-are-the-differences-between-perl-and-java-regex-capabilities) and [this](https://stackoverflow.com/questions/39636124/regular-expression-works-on-regex101-com-but-not-on-prod). – andrewJames Jun 24 '20 at 17:01

1 Answers1

-1

Here is a small working example to solve this problem,

public class MyClass {
public static void main(String args[]) {
  
  String[] tests = {"How AND why", "Try AND succeed AND pass", "Try succeed AND", "Try AND AND succeed AND pass", "how ANDY why"};
  
  for(String s: tests){
      System.out.println(isValid(s));
  }
  
  
  
}

public static boolean isValid(String str){
    String[] splitString = str.split("\\bAND\\b", -1);
    if(splitString.length == 1){
        return false;
    }
    for(String s: splitString){
      if (s.equals(" ") || s.equals("")){
          return false;
      }
    }
    
    return true;
}

}

I am splitting a string using the regex AND. If AND comes in the start or end of a string, there will always be an empty string in the output of str.split("AND", -1). Also, if an AND is followed by another, a space will also be there in str.split("AND", -1). So I check these two conditions in (s.equals(" ") || s.equals(""))

EDIT:

In order to handle strings like how ANDY why you can use word boundaries \b in the regex, which will match the whole word. So a regex like \\bAND\\b will not match the AND part in ANDY. Updated the code above to reflect this.

mettleap
  • 1,390
  • 8
  • 17
  • Hi @mettleap : Thank you for the answer but it is failing in one of the conditions. If I give "how ANDY why" in that case also it is returning true instead of false. Forgot to mention this scenario above. Could you help me with a reg ex for this which will cover all these cases including the one I mentioned in this comment ? – ishita07 Jun 24 '20 at 16:57
  • @ishita07, you can use word boundaries. I updated the answer. Please take a look. :) – mettleap Jun 24 '20 at 17:17