N3WOS
N3WOS

Reputation: 375

Generate a regex for the following pattern

Build a regex to match "${0} and ${1} or ${2}"

Condition

Must have $ followed by {} braces with only digits 0-9. There can be only one such pattern in the string. If there are more than one such patterns then a space followed by either AND or OR can be there.

After OR or AND the same ${} pattern should be present with only digits between the brackets.

Have tried the following \$\{\d*\} | OR | AND | \s+

Upvotes: 0

Views: 104

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174706

You need to form a single regex without logical regex OR operator to match a complete line.

^\$\{\d{1,3}\}(?:\s+(?:and|or)\s+\$\{\d{1,3}\})*$

Since $ is a special character in regex, you need to escape it in-order to match a literal $ symbol.

DEMO

OR

^\$\{\d{1,3}\}(?:\s+(?:and|or)\s+\$\{\d{1,3}\})+$

This expect atleast one and or or present inbetween the $ symbols.

DEMO

String s = "${0} and ${1} or ${2}";
System.out.println(s.matches("^\\$\\{\\d{1,3}\\}(?:\\s+(?:and|or)\\s+\\$\\{\\d{1,3}\\})*$"));
// true

Upvotes: 1

Related Questions