0
$\begingroup$

Is it possible for a regex pattern to return all the 2^n combinations of characters of a string as matches?

For example, if the string is abcd,

then the regex should return the matches:

a
ab
ac
ad
abc
abd
...
...
(16 matches)

I was trying this regex for the string abcd:

(?:.*?)|(?:.*)|(?:.*)|(?:.*)

But this is only returning 5 matches - Demo

Also, regex patterns like this are dependent on the length of the string to match.
Is there any universal generic pattern which is independent of the input string?

$\endgroup$
  • $\begingroup$ Do you mean Perl-style regexes, or regular expressions as used in formal CS? In the former case, a regex always matches a contiguous substring; nothing can ever match ac in your example. $\endgroup$ – Draconis Feb 15 at 4:43
  • $\begingroup$ Oh then what about the latter case? Also you should write it as an answer maybe? $\endgroup$ – Anmol Singh Jaggi Feb 15 at 4:58
  • $\begingroup$ If you clarify which you're interested in, I'll definitely post an answer (though tomorrow at this point) $\endgroup$ – Draconis Feb 15 at 5:50
  • $\begingroup$ Well I did not know there was a difference between the ones implemented in programming languages vs the ones used in formal CS. You said that it is not possible to do it with the former. So I guess you could tell how to do it in the latter. Really curious. $\endgroup$ – Anmol Singh Jaggi Feb 15 at 7:20
  • 2
    $\begingroup$ There seems to be a fundamental misconception to your question: Regexes do not return patterns; they match patterns. If you wish to generate strings, then you need an algorithm that does so, not a regex. $\endgroup$ – dkaeae Feb 15 at 10:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.