3

I need to validate a user input that can include parentheses, the word 'or' and the word 'and'.

The rules are simple:

1- Parentheses can be used anywhere but opening parentheses must have closing one (I might validate this part with code). 2- The expression must never end with 'or' or 'and' within a block. For example:

John and Jane -> OK

John and -> NOT OK

(John and) -> NOT OK

John or -> NOT OK

(John or) -> NOT OK

So it always:

[Optional parentheses] WORD [Optional operation and or][Optional parentheses]

I came up with this but it's not enough but it's a start.

\b\w.*(?=or|and).*\w

That works for the content with parentheses

Note: I don't care about the amount of whitespace between words.

The user can combine these expression blocks multiple times.

2

1 Answer 1

1
^\(?((\w+|\((?1)\))\s+(?>and|or)\s+(\w+|\((?1)\)))\)?$

I didn't think it could be done, but then I found recursion. https://regex101.com/r/aD7dT0/4

EDIT 1: This was broken, fixed it

EDIT 2: Made a better regex + it does parenthesis validation, with the exception of parenthesis around the entire statement

Sign up to request clarification or add additional context in comments.

3 Comments

Im going to clean this up, its pretty gross as of regex101.com/r/aD7dT0/2
TIL all about regex recursion, shoutout to the regex debugger on regex101
Excellent work, did not think it could be done either, excellent!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.