Character classes are a standard way to indicate a set of characters to match in regular expressions. For example, the class
[ab] matches a or b,
[a-z] matches any lower case letter, and
[^a] matches everything but a. For the purpose of this question, classes can contain:
- a sequence of characters to match, where the characters
^must normally be escaped with a
- a range of characters to match, indicated by separating two characters with a
[0-9]. Note that if
-is the first or last character in a class then it need not be escaped, as it's not indicating a range.
- a combination of sequences and ranges: e.g.
[ac-fhk-o]. Note that the class cannot be empty, and if
]is the first character in the class then it need not be escaped.
- a complement match indicated by the first character in the class being
[^a-z]. Note that if
^is not the first character in the class, then it need not be escaped.
Given a non-empty string made up of printable ASCII characters (" " to "~" = 0x20-0x7E), output the shortest character class that matches precisely those characters. The string may contain duplicate characters. Default Input/Output methods apply.
This is code-golf, so shortest code in bytes wins, with all the standard loopholes forbidden.
"the" => "[the]" or "[eht]" etc "faced" => "[ac-f]" or "[c-fa]" "0-121" => "[-0-2]" or "[012-]" etc "]" => "]" "[-^]" => "[^-]" or "^[-]" "[\]" => "[[-\]]" or "\\" or "[\\]"