2

I am totally new to reg-ex and I want to get validation for the string for valid combination of logical operators like ( ! , & , ( , ) , | ) . for Example if & | combined than it should be invalid as AND OR should come together. likewise possible invalid combination are &|, |& , (), !& ,&! etc

like example of below String

1.  (ABC)&(DFG)|!(ZXC) - pass because all operators are correctly combined
2.  !(ABC|DKJ)&VBN - pass
3.  !(ADF&(!&(BER|CTY))|DGH) = failed as !& combined
4.  !(ABC&DKJ)&|VBN - failed as & | combined

I know their several ways like I can use String's contains method to get check and reject if not passed the validation. But I am looking for solution through reg-ex in java

Bhargav Modi
  • 2,605
  • 3
  • 29
  • 49

1 Answers1

1

Just to avoid matching invalid operator combos you can use negative lookahead regex like this:

^(?!.*?(&\\||\\|&|\\(\\)|!&|&!))

Use it with MULTILINE option like this for multiline inputs:

Pattern p = Pattern.compile( "(?m)^(?!.*?(&[!|]|[(|]&|\\(\\)))" );

RegEx Demo

For using it with a string input you can do:

boolean value = input.matches( "(?!.*?(&[!|]|[(|]&|\\(\\))).+" );
anubhava
  • 761,203
  • 64
  • 569
  • 643