Regex permutations without repetition

1k views Asked by At

I need a RegEx to check if I can find a expression in a string.

For the string "abc" I would like to match the first appearance of any of the permutations without repetition, in this case 6: abc, acb, bac, bca, cab, cba.

For example, in this string "adesfecabefgswaswabdcbaes" it'd find a coincidence in the position 7.

Also I'd need the same for permutations without repetition like this "abbc". The cases for this are 12: acbb, abcb, abbc, cabb, cbab, cbba, bacb, babc, bcab, bcba, bbac, bbca

For example, in this string "adbbcacssesfecabefgswaswabdcbaes" it'd find a coincidence in the position 3.

Also, I would like to know how would that be for similar cases.

EDIT I'm not looking for the combinations of the permutations, no. I already have those. WHat I'm looking for is a way to check if any of those permutations is in a given string.

EDIT 2 This regex I think covers my first question ([abc])(?!\1)([abc])(?!\2|\1)[abc]

Can find all permutations(6) of "abc" in any secuence of characters.

Now I need to do the same when I have a repeated character like abbc (12 combinations).

2

There are 2 answers

6
vks On
([abc])(?!\1)([abc])(?!\2|\1)[abc]

You can use this without g flag to get the position.See demo.The position of first group is what you want.

https://regex101.com/r/nS2lT4/41

https://regex101.com/r/nS2lT4/42

1
AudioBubble On

The only reason you might "need a regex" is if you are working with a library or tool which only permits specifying certain kinds of rules with a regex. For instance, some editors can be customized to color certain syntactic constructs in a particular way, and they only allow those constructs to be specified as regular expressions.

Otherwise, you don't "need a regex", you "need a program". Here's one:

// are two arrays equal?
function array_equal(a1, a2) {
  return a1.every(function(chr, i) { return chr === a2[i]; });
}

// are two strings permutations of each other?
function is_permutation(s1, s2) {
  return array_equal(s1.split('').sort(), s2.split('').sort());
}

// make a function which finds permutations in a string
function make_permutation_finder(chars) {
  var len = chars.length;
  return function(str) {
    for (i = 0; i < str.length - len; i++) {
      if (is_permutation(chars, str.slice(i, i+len))) return i;
    }
    return -1; 
  };
}

> finder = make_permutation_finder("abc");
> console.log(finder("adesfecabefgswaswabdcbaes"));
< 6

Regexps are far from being powerful enough to do this kind of thing.

However, there is an alternative, which is precompute the permutations and build a dynamic regexp to find them. You did not provide a language tag, but here's an example in JS. Assuming you have the permutations and don't have to worry about escaping special regexp characters, that's just

regexp = new RegExp(permuations.join('|'));