1

I have a regex, which is suppose to validate strings like R1 AND R2 or R1 AND R3 OR R2 AND R4.

This is my regex:

^[R\d+ (\bAND\b|\bOR\b)]+ R\d+$

Today, I found out that it also accepts strings like "R1AND R2" or "R1 ANDR R2". How can I make sure that my regex must detect spaces between the R\d, AND and OR?

Thanks!

2 Answers 2

3

You're using a character class, it's wrong, use a non capture group instead:

^(?:R\d+\s(?:AND|OR)\s+)*R\d+$
Sign up to request clarification or add additional context in comments.

1 Comment

If you want to explicitly only allow the space character and not all white spaces, use \x20 instead of \s.
1
^R\d+(?:\s+(?:AND|OR)\s+R\d+)*$

Try this.See demo.

https://regex101.com/r/rU8yP6/4

The reaosn yours is not working is because you have included evrything inside [] character class which does not maintian sequence and is just a pool of characters to chose from.

This will match R1 AND R3 OR R2 AND R4 and R1 AND R3 but not R1AND R3

1 Comment

Nice grouping :) Thanks!

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.