/ ( # Assuming you want capture these lines. (?: # Group each line. ^ # Beginning of the line. .{0,40}$\n? # 0 to 40 chars, an end-of line and optional newline. ){1,4} # 1 to 4 lines. (0 will permit an empty match.) ) # Done capturing. /mx; # /m so that ^ anchor works, /x for comments. #### / ( # Assuming you want capture these lines. (?: # Group each line. ^ # Beginning of the line. .{0,40}$ # 0 to 40 characters followed by an end-of-line. \n? # An optional newline. ){1,4} # 1 to 4 lines. (0 will permit an empty match.) ) # Done capturing. /mx; # /m so that ^ anchor works, /x for comments.