Commit 4bc5c39c
4bc5c39cb613Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 3 files · +2 added · ~1 modified
Description
Make regex ^ and $ always line-anchored (Ruby semantics)
In Ruby, ^ and $ are always line anchors: ^ matches at the start
of the string and after any newline, $ at the end and before any
newline, independent of the /m flag (which in Ruby only makes . match
newlines, i.e. DOTALL). The engine gated this line-anchoring on
RE_FLAG_MULTILINE, which is set only for /m, so a default-flag pattern
like /^(\w+) (.+)$/ failed to match a line carrying a trailing newline
(e.g. one yielded by String#each_line): $ only matched at the absolute
end of the string.
This silently broke the common "parse lines -> build a lookup table" shape -- every line except the last (which has no trailing newline) failed to match, so the table kept only the last entry. Surfaced while fixing #1308 (afm / i18n-country-translations parse "key value" lines).
Drop the RE_FLAG_MULTILINE gate on RE_BOL / RE_EOL in both match loops
so ^ / $ line-anchor unconditionally. \A (RE_BOT) / \z (RE_EOT) /
\Z (RE_EOTNL) remain the absolute-boundary anchors, and the /m DOTALL
behaviour (. matching \n) is unchanged, resolved at compile time via
RE_ANY_NL.
Refs #1308
Co-Authored-By: Claude Opus 4.8 [email protected]
Details
- Commit
- 4bc5c39cb613
- Parent
- b3750af68fbd
lib/regexp/re_exec.cmodifiedView file
continue; case RE_BOL: if (sp == s->str || ((s->pat->flags & RE_FLAG_MULTILINE) && sp > s->str && sp[-1] == '\n')) { /* Ruby's `^` is always line-anchored: it matches at the start of the string and after any '\n', independent of the /m flag (which in Ruby only makes `.` match '\n', i.e. DOTALL). `\A` (RE_BOT) is the absolute-start anchor. */ if (sp == s->str || (sp > s->str && sp[-1] == '\n')) { pc++; continue; } return; case RE_EOL: if (sp == s->str_end || ((s->pat->flags & RE_FLAG_MULTILINE) && *sp == '\n')) { /* Ruby's `$` is always line-anchored: it matches at the end of the string and before any '\n', independent of /m. `\z` (RE_EOT) / `\Z` (RE_EOTNL) are the absolute-end anchors. */ if (sp == s->str_end || *sp == '\n') { pc++; continue; } return; } case RE_BOL: if (sp != str && !(pat->flags & RE_FLAG_MULTILINE && sp > str && sp[-1] == '\n')) return FALSE; /* Ruby `^`: always line-anchored (start of string or after '\n'), independent of /m. See the RE_BOL note in the NFA loop above. */ if (sp != str && !(sp > str && sp[-1] == '\n')) return FALSE; pc++; break; case RE_EOL: if (sp != str_end && !(pat->flags & RE_FLAG_MULTILINE && *sp == '\n')) return FALSE; /* Ruby `$`: always line-anchored (end of string or before '\n'), independent of /m. */ if (sp != str_end && *sp != '\n') return FALSE; pc++; break;test/regexp_line_anchors.rbaddedView file
Loading diff…
test/regexp_line_anchors.rb.expectedaddedView file
Loading diff…