Is there a way to write a regex to match a string that only contains certain characters, and never repeats those characters? I already wrote some code using a set to implement this, but would like to know if there's a regex way to do it.
So for example, if I only wanted a string that contains [A,B,C], and I want to match to a string that never duplicates any of those characters, eg A, B, C, AB, AC, B, BC, ABC, and so on, but never matches AA, BB, CC, etc
Thanks!
\/ ------- will match for a "/" ^\/ ----- will match for a "/" at the beginning of the line. [^\/] ------ ^ inside a [ ] will be for negation(opposite of). it will match for anything except a "/"
\d (digit) matches any single digit (same as [0-9] ). The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ). \s (space) matches any single whitespace (same as [ \t\n\r\f] , blank, tab, newline, carriage-return and form-feed).
The backslash in a regular expression precedes a literal character. You also escape certain letters that represent common character classes, such as \w for a word character or \s for a space.
A regular expression followed by an asterisk ( * ) matches zero or more occurrences of the regular expression. If there is any choice, the first matching string in a line is used.
That's easy to do with a negative lookahead assertion:
^(?!.*(.).*\1)[ABC]+$
matches exactly as you described.
Test it live on regex101.com.
Explanation:
^ # Start of the string
(?! # Assert that it's impossible to match...
.* # Any number of characters (including zero)
(.) # followed by one character (remember this one in group 1)
.* # that's followed by any number of characters
\1 # and the same character as before
) # End of lookahead
[ABC]+ # Match one or more characters from this list
$ # until the end of the string
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