@@ -263,6 +263,22 @@ var replaceFuncTests = []ReplaceFuncTest{
263263 {"[a-c]*" , func (s string ) string { return "x" + s + "y" }, "defabcdef" , "xydxyexyfxabcydxyexyfxy" },
264264}
265265
266+ type ReplaceFuncSubmatchTest struct {
267+ pattern string
268+ replacement func ([]string ) string
269+ input , output string
270+ }
271+
272+ var replaceFuncSubmatchTests = []ReplaceFuncSubmatchTest {
273+ {"[a-c]+" , func (g []string ) string { return "x" + g [0 ] + "y" }, "defdef" , "defdef" },
274+ {"[a-c]" , func (g []string ) string { return "x" + g [0 ] + "y" }, "defabcdef" , "defxayxbyxcydef" },
275+ {"[a-c]+" , func (g []string ) string { return "x" + g [0 ] + "y" }, "defabcdef" , "defxabcydef" },
276+ {"[a-c]*" , func (g []string ) string { return "x" + g [0 ] + "y" }, "defabcdef" , "xydxyexyfxabcydxyexyfxy" },
277+ {"<<placeholder\\ .(\\ d+)>>" , func (g []string ) string { return "-" + g [1 ] + "-" }, "a<<placeholder.1>>b<<placeholder.2>>c<<placeholder.3>>d" , "a-1-b-2-c-3-d" },
278+ {"(\\ w+)\\ s+(\\ w+)" , func (g []string ) string { return g [2 ] + " " + g [1 ] }, "hello world" , "world hello" },
279+ {"[aeiou]" , func (g []string ) string { return "" }, "hello" , "hll" },
280+ }
281+
266282func TestReplaceAll (t * testing.T ) {
267283 for _ , tc := range replaceTests {
268284 re , err := Compile (tc .pattern )
@@ -350,6 +366,36 @@ func TestReplaceAllFunc(t *testing.T) {
350366 }
351367}
352368
369+ func TestReplaceAllSubmatchFunc (t * testing.T ) {
370+ for _ , tc := range replaceFuncSubmatchTests {
371+ re , err := Compile (tc .pattern )
372+ if err != nil {
373+ t .Errorf ("Unexpected error compiling %q: %v" , tc .pattern , err )
374+ continue
375+ }
376+ actual := re .ReplaceAllStringSubmatchFunc (tc .input , tc .replacement )
377+ if actual != tc .output {
378+ t .Errorf ("%q.ReplaceFunc(%q,fn) = %q; want %q" ,
379+ tc .pattern , tc .input , actual , tc .output )
380+ }
381+ // now try bytes
382+ actual = string (re .ReplaceAllSubmatchFunc (
383+ []byte (tc .input ),
384+ func (g [][]byte ) []byte {
385+ stringGroups := make ([]string , len (g ))
386+ for i , group := range g {
387+ stringGroups [i ] = string (group )
388+ }
389+ return []byte (tc .replacement (stringGroups ))
390+ },
391+ ))
392+ if actual != tc .output {
393+ t .Errorf ("%q.ReplaceFunc(%q,fn) = %q; want %q" ,
394+ tc .pattern , tc .input , actual , tc .output )
395+ }
396+ }
397+ }
398+
353399type MetaTest struct {
354400 pattern , output , literal string
355401 isLiteral bool
0 commit comments