Regex is like ((AND|OR)([!=><]+)(.*))+ Input is like $check = "AND=>1536463OR## AND!==!>!!LKJKJIOJJ182873KLJJyuukjljkOR!<><><><><=!Blah OR==!=!Hmm, could this be right?AND>>>>>>>this could be a problem #### AND,=>,1536463 OR,<,foobar OR,=,5 #### $_ = "OR=5AND=>1536463OR<=]?|[><]=?|!=|<>) #one of = => =< == > < >= .... ( #capture all within... (?: # group for quantifier (?! # not followed by (?:AND|OR) # AND or OR (?:=[><]?|[><]=?|[!=]=)# one of = => =< ... ) # any of the inside . # match any char.. )+ # 1 or more of the above ) #and return it.. /xgms) { #ignore spaces, repeated, #multiline, . matches all # and if it all worked out then... print "$1 $2 $3\n"; } # outputs # OR = 5 # AND => 1536463 # OR < foORobar # OR = 5 #### my $opers='=[><=!]?|[>|[<>]'; while (m/(AND|OR)($opers)((?:(?!(?:AND|OR)(?:$opers)).)+)/xgms) { print "$1 $2 $3\n"; }