Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a regular expression that will match characters in any order?

Tags:

regex

ruby

I'm trying to write a regular expressions that will match a set of characters without regard to order. For example:

str = "act" 
str.scan(/Insert expression here/)

would match:

cat
act
tca
atc
tac
cta

but would not match ca, ac or cata.

I read through a lot of similar questions and answers here on StackOverflow, but have not found one that matches my objectives exactly.

To clarify a bit, I'm using ruby and do not want to allow repeat characters.

like image 509
Mutuelinvestor Avatar asked Dec 15 '22 14:12

Mutuelinvestor


1 Answers

Here is your solution

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

See it here on Regexr

^                  # matches the start of the string
    (?:            # open a non capturing group 
        ([act])    # The characters that are allowed and a capturing group
        (?!.*\1)   # That character is matched only if it does not occur once more, Lookahead assertion
    ){3}           # Defines the amount of characters
$

The only special think is the lookahead assertion, to ensure the character is not repeated.

^ and $ are anchors to match the start and the end of the string.

like image 81
stema Avatar answered Feb 15 '23 23:02

stema