Search code examples
javascriptregexregex-lookaroundsregex-greedy

Regex to match all combinations of a given string


I am trying to make a regex to matches all the combinations of a given string. For example of the string is "1234", answers would include:

  1. "1"
  2. "123"
  3. "4321"
  4. "4312"

Nonexamples would include:

  1. "11"
  2. "11234"
  3. "44132"

If it matters, the programming language I am using is javascript.

Thank you for any help.


Solution

  • You don't need to use regex for this. The snippet below does the following:

    1. Loop over possible combinations (a => s) (1, 123, 4321, etc.)
    2. Copy the current combination so as not to overwrite it (s2 = s)
    3. Loop over the characters of test string (x => ch) (1234 => 1, 2, 3, 4)
    4. Replace common characters in the combination string shared with the test string (s2.replace)
      • For example in the combination 1, the 1 will be replaced when the loop gets to the character 1 in 1234 resulting in an empty string
    5. If the combination string's length reaches 0 (s2.length == 0) write the result to the console and break out of the loop (no point in continuing to attempt to replace on an empty string)

    const x = "1234"
    const a = ["1","123","4321","4312","11","11234","44132"]
    
    a.forEach(function(s) {
      var s2 = s
      for(var ch of x) {
        s2 = s2.replace(ch, '')
        if(s2.length == 0) {
          console.log(s);
          break;
        }
      }
    })

    Results:

    1
    123
    4321
    4312