Skip to content

Commit

Permalink
Fix off-by-one in regex replace and add test (#2144)
Browse files Browse the repository at this point in the history
Co-authored-by: amylizzle <[email protected]>
Co-authored-by: wixoa <[email protected]>
  • Loading branch information
3 people authored Dec 18, 2024
1 parent 64c5684 commit 5483541
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
20 changes: 20 additions & 0 deletions Content.Tests/DMProject/Tests/Regex/regex_find_replace.dm
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
var/models = "/obj/cable/brown{\n\ticon_state = \"2-8\"\n\t},\n/obj/cable/brown{\n\ticon_state = \"4-8\"\n\t},\n/turf/simulated/floor/orangeblack,\n/area/station/devzone"
var/result_match = "/obj/cable/brown{\n\ticon_state = \"1\"\n\t},\n/obj/cable/brown{\n\ticon_state = \"2\"\n\t},\n/turf/simulated/floor/orangeblack,\n/area/station/devzone"

/proc/RunTest()
var/list/originalStrings = list()
var/regex/noStrings = regex(@{"(["])(?:(?=(\\?))\2(.|\n))*?\1"})
var/stringIndex = 1
var/found
do
found = noStrings.Find(models, noStrings.next)
if(found)
var indexText = {""[stringIndex]""}
stringIndex++
var match = copytext(noStrings.match, 2, -1) // Strip quotes
models = noStrings.Replace(models, indexText, found)
originalStrings[indexText] = (match)
while(found)
ASSERT(models == result_match)
ASSERT(originalStrings ~= list("\"1\"" = "2-8", "\"2\"" = "4-8"))
ASSERT(stringIndex == 3)
2 changes: 1 addition & 1 deletion OpenDreamRuntime/Procs/Native/DreamProcNativeRegex.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ DreamValue DoTextReplace(string replacement) {
if(!regex.IsGlobal) {
var match = regex.Regex.Match(haystackString, Math.Clamp(start - 1, 0, haystackSubstring.Length));
if (!match.Success) return new DreamValue(haystackString);
regexInstance.SetVariable("next", new DreamValue(match.Index + Math.Max(replacement.Length, 1)));
regexInstance.SetVariable("next", new DreamValue(match.Index + Math.Max(replacement.Length, 1) + 1));
}

string replaced = regex.Regex.Replace(haystackSubstring, replacement, regex.IsGlobal ? -1 : 1,
Expand Down

0 comments on commit 5483541

Please sign in to comment.