I am writing a Java code that finds a way out from any maze and I need a class that checks generated mazes. Only ., #, S, X characters are allowed.
. and # - one and more occurrences at any place of the string are allowed
S and X - one and not more than one occurrence at any place of the string is allowed.
^[#//.]+$ - regex for the first condition,
But I cannot implement the second one.
The maze input looks like this:
.......S..#.
.....###....
..X.........
. - empty space, # - wall, S - start, X - exit
You can use negative lookahead groups, written like (?!...), to accomplish this, like so:
^(?!.*S.*S)(?!.*X.*X)[SX.#]+$
Demo
This accepts any set of characters from your set (S, X, ., #) from the start of the string using the ^ and [SX.#]+. But it rejects any string containing 2 Ss ((?!.*S.*S)) or 2 Xs ((?!.*X.*X)).
Note that this actually checks both of your conditions. You don't really need 2 regexes here. Based on your example maze, though, it looks like your input can span multiple lines. In that case, you need to add \n inside the final character class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With