Source file src/regexp/syntax/example_test.go

     1  // Copyright 2026 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package syntax_test
     6  
     7  import (
     8  	"fmt"
     9  	"regexp/syntax"
    10  )
    11  
    12  func ExampleParse() {
    13  	re, err := syntax.Parse(`(go|lang)+`, syntax.Perl)
    14  	if err != nil {
    15  		panic(err)
    16  	}
    17  
    18  	fmt.Println("String:", re.String())
    19  	fmt.Println("Op:", re.Op)
    20  	fmt.Println("Sub expressions:", len(re.Sub))
    21  
    22  	// Walk the public parse tree to inspect its structure.
    23  	var printTree func(*syntax.Regexp, string)
    24  	printTree = func(re *syntax.Regexp, indent string) {
    25  		fmt.Printf("%s%s: %s\n", indent, re.Op, re)
    26  		for _, sub := range re.Sub {
    27  			printTree(sub, indent+"  ")
    28  		}
    29  	}
    30  	printTree(re, "")
    31  
    32  	// Output:
    33  	// String: (go|lang)+
    34  	// Op: Plus
    35  	// Sub expressions: 1
    36  	// Plus: (go|lang)+
    37  	//   Capture: (go|lang)
    38  	//     Alternate: go|lang
    39  	//       Literal: go
    40  	//       Literal: lang
    41  }
    42  

View as plain text