Home > Blockchain >  Regular expression that matches a single word in any order
Regular expression that matches a single word in any order

Time:12-16

After a long, unsuccessful search I am starting to wonder if what I am looking for is possible, I would like a regular expression which requires that each letter chosen is mandatory but only once and in any order.

Example : ^[abc]{3}$

The result I expect would be that it matches only that :

abc, bac, cba, acb

While I get :

acc, abb, cca, aab

Do you see where I am going with this?

CodePudding user response:

You may use a regex like this with a negative lookahead of the matched character in a back-reference:

^(?:([abc])(?!.*\1)){3}$

RegEx Demo

CodePudding user response:

Here is another way.

^(?!.*([abc]).*\1)[abc]{3}$

Demo

The negative lookahead

(?!.*([abc]).*\1)

asserts that no character is repeated and

[abc]{3}

together with the two anchors asserts that the string has a length of three and is composed of the characters in the character class.

  • Related