Perl (111 110 122 characters)
use Regexp::Assemble;@ARGV=shift;my$r=new Regexp::Assemble;chomp,add$r "^\Q$_\E\$"while<>;$_=as_string$r;s/\(\?:/(/g;print
This uses CPAN module called Regexp::Assemble
in order to optimize the regular expressions. Because what is the better language for regular expressions then Perl.
Also, readable version, just for fun (made with help of -MO=Deparse
).
use Regexp::Assemble;
my $r = Regexp::Assemble->new;
while (<>) {
chomp($_);
$r->add("^\Q$_\E\$");
}
$_ = $r->as_string;
# Replace wasteful (?:, even if it's technically correct.
s/\(\?:/(/g;
print $_;
Sample output (I did CTRL-D after item4
).
$ perl assemble.pl
item1
atem2
item3
item4
^(item[134]|atem2)$
Also, as a bonus, I'm writing the regex for every word in the question.
^(a((ttemp)?t|llowed\.|rbitrary)?|\/\^item1\|atem2\|item3\|item4\$\/|s(ho(rt,|uld)|imilar)|p((air|lay)s|rogram)|(Writ|mak|Th)e|l(ists\.|east)|o([fr]|utputs)|t(h(at|e)|o)|(jus|no)t|regex|golf|with|is)$
Also, list of presidents (262 bytes).
^(((J(effer|ack|ohn)s|W(ashingt|ils)|Nix)o|Van Bure|Lincol)n|C(l(eveland|inton)|oolidge|arter)|H(a(r(rison|ding)|yes)|oover)|M(cKinley|adison|onroe)|T(a(ylor|ft)|ruman)|R(oosevelt|eagan)|G(arfield|rant)|Bu(chanan|sh)|P(ierce|olk)|Eisenhower|Kennedy|Adams|Obama)$
/^item1|atem2|item3|item4$/
probably has unintended precedence (string has to either begin withitem1
, containatem2
, containitem3
, or end withitem4
). \$\endgroup\$