#!/usr/bin/perl -w use strict; while () { my ($host, $test) = ($_ =~ m/ ( # Start first capture [\w\-]+ # One or more alphanum or hyphens (?: # non-capturing lookahead ,my-domain,com # Literal string )? # Make it optional ) # End of first capture (?: # non-capturing lookahead [\w\-,]+ # One or more alpanum or hyphens )? # Make it optional \. # A literal period ( # Start second capture [a-z]+ # One or more lowercase chars ) # End second capture /x) or print "Cannot parse $_\n" and next; print "Host:$host Test:$test\n"; } __DATA__ hosta-sel-kr-1,my-domain,net.testa hostb-sel-kr-1,my-domain,net.testb hostc-sel-kr-1,my-domain,com.testa hostd-sel-kr-1,my-domain,com.testc hoste-sel-kr-1,my-domain,net.testxyz hosta-mel-au-1,my-domain,net.testabc hosta-mel-au-1,my-domain,net.testdef hostxyz.testabc someotherhost.someothertest