create table foo ( somevar1 sometype, somevar2 sometype null, somevar3 sometype not null, somevar4 sometype(20), somevar5 sometype(20) null, somevar6 sometype(10)) #### $str =~ s{ (create\s+table\s+\w+\s*\() # "create table foo (", save as $1 ( # Grab this pattern (each of the create table variables), save as $2 ( # Save as $3 \s* # Any spaces \w+ # Variable name \s+ # At least one space \w+ # Variable type ( # Optional (nnn) for character string types, save as $4 \( # Literal open paren \d+ # Any number of digits \) # Literal close paren )? # The ? makes it optional \s* # Any spaces ) # "varname vartype " (not the null/not null part) ( # Save as $5 [\w\s]* # Any words and/or spaces ("null" or "not null", specifically) ) ( # Save as $6 ,? # Optional comma (optional as it may be the last element) \s* # Any spaces ) )+ # Match this whole section at least once (\s*\)\s*) # Closing paren for create table block with surrounding whitespace, save as $7 } { print $1; print $3; if ($5 =~ /null/i) { print $5; } else { print " NOT NULL"; } print $6; print $7; }gex; # Output: create table foo (somevar6 sometype(10) NOT NULL)