ContainsAny Checks A Character Class

Test whether a string contains any rune from a class with strings.ContainsAny, then contrast it with IndexAny which reports the matching byte offset.

GoForm Validation

Code

snippet
package main

import (
	"fmt"
	"strings"
)

func main() {
	// 验证输入里是否出现任一非法字符(字符类,不是子串)
	forbidden := "!@#$%"
	inputs := []string{"deploy", "deploy!", "no spaces", "user@host"}

	for _, input := range inputs {
		bad := strings.ContainsAny(input, forbidden)
		pos := strings.IndexAny(input, forbidden)
		fmt.Printf("%-12q bad=%-5v firstAt=%d\n", input, bad, pos)
	}

	// 空字符类恒 false:没有任何字符可匹配
	fmt.Println("empty class:", strings.ContainsAny("anything", ""))
}

Walkthrough of the flow

The snippet is organized around the function main.

A single loop drives the file — for _, input := range inputs.

Watch out for

  • No third-party code involved — each API comes with the runtime.

Putting it to use

Entry signature: func main()

The output walks through the steps in order: empty class:.

The load-bearing lines

for _, input := range inputs {
	bad := strings.ContainsAny(input, forbidden)
	pos := strings.IndexAny(input, forbidden)
	fmt.Printf("%-12q bad=%-5v firstAt=%d\n", input, bad, pos)
}

Interactive Tools for This Topic

FAQ

What does ContainsAny Checks A Character Class print when run?
Invoke the file as-is — the `empty class:` prefixes identify which step printed each line.