Today I learned that a regex can match permutations of a given string.

Update: Oops, I had the terms reversed on the regex, it should be $i =~ $x .... I've corrected it, but it doesn't really change the results.

For single characters without repeats, such as any permutation of 'abc', this seems the shortest, most readable method:

@x = glob('{a,b,c}'x3); # for testing: all permutations, plus many mor +e $x = '(?:([a-c])(?!.*\1)){3}'; # regex for $i (@x) { $i =~ $x and say $i; # was $x =~ $i }

which outputs:

abc acb bac bca cab cba

For single character, with limited repeats, such as any permutation of 'aabbcc', a slightly different approach is needed. I tried the following, but it matches almost everything. I suspect there's some unexpected behavior in the backtracking?

@x = glob('{a,b,c}'x6); $x = '(?:a()|a()|b()|b()|c()|c()){6}\1\2\3\4\5\6'; # limited repeats a +llowed for $i (@x) { $i =~ $x and say $i; # was $x =~ $i }

which outputs 540 of the 728 strings given (at least 1 of each char is present):

aaaabc aaaacb aaabac aaabbc aaabca ... cccbba cccbca ccccab ccccba

Is there some other magic to DWIM?

For nonrepeating, multichar permutations, even when individual chars are shared between tokens, this approach works:

@x = glob('{abc,bcd,cde}'x3); # permutations of 'abc/bcd/cde' $x = '(?:abc()|bcd()|cde()){3}\1\2\3'; for $i (@x) { $i =~ $x and say $i; # was $x =~ $i }

which outputs:

abcbcdcde abccdebcd bcdabccde bcdcdeabc cdeabcbcd cdebcdabc

I found this here on Stack Overflow.

-QM
--
Quantum Mechanics: The dreams stuff is made of

-QM
--
Quantum Mechanics: The dreams stuff is made of


In reply to Matching permutations with regex by QM

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.