예제 #1
0
func ExampleAlt() {
	var r interface{}
	var ok bool
	prt := func() {
		if ok {
			fmt.Printf("Result: %s\n", utf88.Surr(r.(utf88.Text)))
		} else {
			fmt.Printf("Error: %v\n", r)
		}
	}

	lower := kern.Regexp(`\p{Ll}`)
	upper := kern.Regexp(`\p{Lu}`)
	digit := kern.Regexp(`\p{Nd}`)

	p := kern.Alt(lower, digit)
	q := kern.Alt(lower, digit, upper)

	t := utf88.Text("7ef")
	u := utf88.Text(";ef")

	r, ok = kern.ParseText(p, t)
	prt()

	r, ok = kern.ParseText(p, u)
	prt()

	r, ok = kern.ParseText(q, t)
	prt()

	// Output:
	// Result: 7
	// Error: No alternatives selected.
	// Result: 7
}
예제 #2
0
func ExampleTry() {
	p := kern.Flatten(kern.Regexp(`\pL`), kern.Regexp(`\pL`))
	q := kern.Flatten(kern.Regexp(`\pL`), kern.Regexp(`\pN`))

	t := utf88.Text("a7bcde")

	var r interface{}
	var ok bool
	prt := func() {
		if ok {
			fmt.Printf("Result: %s\n", utf88.Surr(r.(utf88.Text)))
		} else {
			fmt.Printf("Error: %v\n", r)
		}
	}

	r, ok = kern.ParseText(kern.Alt(p, q), t)
	prt()

	r, ok = kern.ParseText(kern.Alt(kern.Try(p), q), t)
	prt()

	// Output:
	// Error: Unexpected 7 input.
	// Result: a7
}
예제 #3
0
func ExampleFwdWithParams() {
	var expr func(...interface{}) kern.Parser

	paren := func(as ...interface{}) kern.Parser {
		return kern.SeqRight(kern.Token(utf88.Text(string('('))),
			kern.SeqLeft(kern.FwdWithParams(expr, as...), // FwdWithParams will evaluate passed expression lazily
				kern.Token(utf88.Text(string(')')))))
	}
	expr = func(as ...interface{}) kern.Parser { // will parse string enclosed in parenthesis pairs to any depth
		return kern.Alt(kern.Token(utf88.Text(string('a'))),
			paren(as...))
	}

	t := utf88.Text("(((a)))")
	r, ok := kern.ParseText(expr(101, 102), t) // call expr with extra (unused in this e.g.) args
	if ok {
		fmt.Printf("Result: %s\n", utf88.Surr(r.(utf88.Text)))
	} else {
		fmt.Printf("Error: %v\n", r)
	}

	// Output:
	// Result: a
}
예제 #4
0
func ExampleFwd() {
	var expr func() kern.Parser

	paren := func() kern.Parser {
		return kern.SeqRight(kern.Token(utf88.Text(string('('))),
			kern.SeqLeft(kern.Fwd(expr), // Fwd will evaluate passed expression lazily
				kern.Token(utf88.Text(string(')')))))
	}
	expr = func() kern.Parser { // will parse string enclosed in parenthesis pairs to any depth
		return kern.Alt(kern.Token(utf88.Text(string('a'))),
			paren())
	}

	t := utf88.Text("(((a)))")
	r, ok := kern.ParseText(expr(), t)
	if ok {
		fmt.Printf("Result: %s\n", utf88.Surr(r.(utf88.Text)))
	} else {
		fmt.Printf("Error: %v\n", r)
	}

	// Output:
	// Result: a
}