Product SiteDocumentation Site

2.5. Regular expressions

A common gotcha in Ruby regular expressions relates to anchors marking the begninning and the end of a string. Specifically, ^ and $ refer to the beginning and the end of a line, rather then a string. If regular expression like /^[a-z]+$ is used to whitelist user input, attacker can bypass it by including newline. To match the beginning and the end of a string use anchors \A and \z.
>> puts 'Exploited!' if /^benign$/ =~ "benign\n with exploit"
=> nil
>> puts 'Exploited!' if /\Abenign\z/ =~ "benign\n with exploit"
=> nil