88 Regular expressions in Ruby can use anchors to match the beginning and end of a string.
99 However, if the <code >^</code > and <code >$</code > anchors are used,
1010 the regular expression can match a single line of a multi-line string.
11+ This allows bad actors to bypass your regular expression checks and inject malicious input.
1112 </p >
1213 </overview >
1314
1415 <recommendation >
1516 <p >
16- Use the <code >\A</code > and <code >\z</code > anchors to match the beginning and end of a string,
17- as these will always match the beginning and end of the string, even if the string contains newlines.
17+ Use the <code >\A</code > and <code >\z</code > anchors since these anchors will always
18+ match the beginning and end of the string, even if the string contains newlines.
1819 </p >
1920 </recommendation >
2021
2122 <example >
2223
2324 <p >
24- The following example code uses a regular expression to check that a string contains only digits.
25+ The following (bad) example code uses a regular expression to check that a string contains only digits.
2526 </p >
2627
27- <sample language =" ruby" >
28- def bad(input)
29- raise "Bad input" unless input =~ /^[0-9]+$/
30-
31- # ....
32- end
33- </sample >
28+ <sample src =" examples/missing_full_anchor_bad.rb" />
3429
3530 <p >
3631 The regular expression <code >/^[0-9]+$/</code > will match a single line of a multi-line string,
3732 which may not be the intended behavior.
38- To match the entire string, the regular expression should be <code >\A[0-9]+\z</code >.
33+ The following (good) example code uses the regular expression <code >\A[0-9]+\z</code > to match the entire input string .
3934 </p >
4035
41- <sample language =" ruby" >
42- def good(input)
43- raise "Bad input" unless input =~ /\A[0-9]+\z/
44-
45- # ....
46- end
47- </sample >
36+ <sample src =" examples/missing_full_anchor_good.rb" />
4837
4938 </example >
5039
5140 <references >
5241 <li >
53- RDoc Documentation : <a href =" https://ruby-doc.org/3.2.0/Regexp.html#class-Regexp-label-Anchors" >Anchors</a >
42+ Ruby documentation : <a href =" https://ruby-doc.org/3.2.0/Regexp.html#class-Regexp-label-Anchors" >Anchors</a >
5443 </li >
5544 </references >
5645</qhelp >
0 commit comments