Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for exact one character occurrence at any place of the string

Tags:

java

regex

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.

  1. . and # - one and more occurrences at any place of the string are allowed

  2. 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

like image 594
dimmxx Avatar asked Jan 29 '26 19:01

dimmxx


1 Answers

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.

like image 105
elixenide Avatar answered Jan 31 '26 09:01

elixenide



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!