# Returning all the combinations of a string using regex

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
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?

• 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. – Draconis Feb 15 '19 at 4:43
• Oh then what about the latter case? Also you should write it as an answer maybe? – Anmol Singh Jaggi Feb 15 '19 at 4:58
• If you clarify which you're interested in, I'll definitely post an answer (though tomorrow at this point) – Draconis Feb 15 '19 at 5:50
• 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. – Anmol Singh Jaggi Feb 15 '19 at 7:20
• 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. – dkaeae Feb 15 '19 at 10:38