-1

Example: I need a regex pattern which accepts patterns in the following combination

  1. String should accept both with braces and without braces, first word of every string should start either with NOT or without NOT.
  2. Every word in the sentence should be followed by AND/OR.

  3. Eg: “(NOT cbe AND (man OR hen))

  • 2
    what is your regular expression so far? – Aimee Borda Nov 27 '16 at 07:36
  • 5
    Since you are trying to handle nested structures regex is not best tool. You are most likely looking for parser. Maybe try to create one with ANTLR. – Pshemo Nov 27 '16 at 07:38
  • 1
    @Pshemo Wish I could upvote your comment more than once. I have also gotten good mileage from a tool called [Javaluator](http://javaluator.sourceforge.net/en/home/). – Tim Biegeleisen Nov 27 '16 at 07:40
  • 1
    Now you have two problems. Obligatory reference: http://stackoverflow.com/a/1732454/18157 – Jim Garrison Nov 27 '16 at 07:54
  • (((?:[(]* ?[a-z][a-z]+ ?[)]*)|[(]* ?(NOT) (?:[(]* ?[a-z][a-z]+ ?[)]*) ?[)]*)( (AND|OR) ((?:[(]* ?[a-z][a-z]+ ?[)]*)|[(]* ?(NOT) (?:[(]* ?[a-z][a-z]+ ?[)]*) ?[)]*))*) this is my current regex @aimee – Mahe Mohan Nov 27 '16 at 08:00

1 Answers1

0

Question isn't clear, but based on information provided: /(NOT |)([A-Z-a-z])\w+ (AND|OR) (([A-Z-a-z])\w+ (AND|OR) ([A-Z-a-z])\w+)/g

works fine for below cases: (NOT cbe AND (man OR hen)) (cbe AND (man OR hen)) NOT cbe AND (man OR hen)

Here is the link: http://regexr.com/3eoik

Kanhaiya
  • 58
  • 5
  • I believe in Java regex a / (slash) matches itself, so I don’t understand why you begin with it. I played a bit around with your link, and I think it behaves funnily in some situations. It finds no match in “(NOT cbe AND man OR hen)”. Neither in “(NOT c AND (man OR hen))”. – Ole V.V. Nov 27 '16 at 09:14