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.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Character Frequency AnalyzerCount how often each character appears in a text, with Unicode code points, optional case folding, and whitespace exclusion.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.