Home > Mobile >  Regex: match only chars which aren't the same in a string
Regex: match only chars which aren't the same in a string

Time:11-07

Got a question regarding regex matching in Java. Given is a string with a defined length. Now I want to check with a matcher if every char contained in that String is different.

For example (only pass of length = 8):

String a = "abcdefgz" -> pass
String b = "aacdefgz" -> fail
String c = "abcdefghz" -> fail

So matching the length would simply be:

"^[a-zA-Z]{8}$"

But to get it working in combination with the condition that every contained char needs to be unique is quite tough.

CodePudding user response:

Well, this one matches strings containing duplicates. This is basically the reverse of what you are looking for.

.*(.) .*\1.*

If it's suitable, you can pick string that do not match this expression. Or maybe check regex negative match to improve it.

  • Related