Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for no duplicate characters from a limited character pool

Tags:

regex

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!

like image 737
cliffycheng Avatar asked Oct 20 '14 16:10

cliffycheng


People also ask

What does \/ mean in RegEx?

\/ ------- 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 "/"

What does \d do in RegEx?

\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).

How do you escape special characters in RegEx?

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.

Which RegEx character matches zero or more of the previous character?

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.


1 Answers

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
like image 122
Tim Pietzcker Avatar answered Sep 25 '22 18:09

Tim Pietzcker