To see if a string is a permutation of ABCDEFG
, it's easy with negative lookahead and capturing group to enforce no duplicates:
^(?!.*(.).*\1)[A-G]{7}$
You don't need the anchors if you use String.matches()
in Java. Here's a test harness:
String[] tests = {
"ABCDEFG", // true
"GBADFEC", // true
"ABCADFG", // false
};
for (String test : tests) {
System.out.format("%s %b%n", test,
test.matches("(?!.*(.).*\\1)[A-G]{7}")
);
}
Basically, [A-G]{7}
, but also (?!.*(.).*\1)
. That is, no character is repeated.
Here's a test harness for the assertion to play around with:
String[] tests = {
"abcdeb", // "(b)"
"abcdefg", // "abcdefg"
"aba", // "(a)"
"abcdefgxxxhijyyy" // "(y)"
};
for (String test : tests) {
System.out.println(test.replaceAll("(?=.*(.).*\\1).*", "($1)"));
}
The way it works is by trying to match .*(.).*\1
, that is, with .*
in between, a captured character (.)
that appears again \1
.
See also