蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 Go 1.22 regexp 编译/匹配/查找/替换/分割及元字符转义离线实验

GO本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。explore_regex.go
explore_regex.go146 行
package main

import (
	"encoding/json"
	"fmt"
	"os"
	"reflect"
	"regexp"
	"runtime"
)

type Case struct {
	Name     string `json:"name"`
	Summary  string `json:"summary"`
	Expected any    `json:"expected"`
	Actual   any    `json:"actual"`
	Passed   bool   `json:"passed"`
}

type Report struct {
	Version string `json:"version"`
	Cases   []Case `json:"cases"`
}

func makeCase(name, summary string, expected, actual any) Case {
	return Case{
		Name:     name,
		Summary:  summary,
		Expected: expected,
		Actual:   actual,
		Passed:   reflect.DeepEqual(expected, actual),
	}
}

func main() {
	var cases []Case

	// Case 1: Compile vs MustCompile & MatchString
	alnum := regexp.MustCompile(`^[a-zA-Z0-9]+$`)
	_, badErr := regexp.Compile(`[unclosed`)
	mustPanicked := false
	func() {
		defer func() {
			if recover() != nil {
				mustPanicked = true
			}
		}()
		_ = regexp.MustCompile(`[unclosed`)
	}()

	actual1 := map[string]any{
		"match_ok":      alnum.MatchString("Hello123"),
		"match_fail":    alnum.MatchString("Hello 123!"),
		"compile_err":   badErr != nil,
		"must_panicked": mustPanicked,
	}
	expected1 := map[string]any{
		"match_ok":      true,
		"match_fail":    false,
		"compile_err":   true,
		"must_panicked": true,
	}
	cases = append(cases, makeCase(
		"regex_compile_and_match",
		"核对 regexp.Compile 错误返回、MustCompile panic 行为及 MatchString 匹配校验",
		expected1, actual1,
	))

	// Case 2: FindString and FindAllString
	digits := regexp.MustCompile(`\d+`)
	sample := "我有 3 个苹果和 5 个香蕉"
	actual2 := map[string]any{
		"find_first":  digits.FindString(sample),
		"find_all":    digits.FindAllString(sample, -1),
		"find_limit1": digits.FindAllString(sample, 1),
	}
	expected2 := map[string]any{
		"find_first":  "3",
		"find_all":    []string{"3", "5"},
		"find_limit1": []string{"3"},
	}
	cases = append(cases, makeCase(
		"regex_find_and_find_all",
		"核对 FindString 提取首个数字子串与 FindAllString 提取全部/限量匹配项",
		expected2, actual2,
	))

	// Case 3: ReplaceAllString and Split
	spaces := regexp.MustCompile(`\s+`)
	comma := regexp.MustCompile(`,`)
	actual3 := map[string]any{
		"replaced": spaces.ReplaceAllString("Hello    World", " "),
		"split":    comma.Split("apple,banana,orange", -1),
	}
	expected3 := map[string]any{
		"replaced": "Hello World",
		"split":    []string{"apple", "banana", "orange"},
	}
	cases = append(cases, makeCase(
		"regex_replace_and_split",
		"核对 ReplaceAllString 压缩连续空白及 Split 按模式切分字符串",
		expected3, actual3,
	))

	// Case 4: Basic regex metacharacters and escaping (quoted vs raw string)
	reQuoted := regexp.MustCompile("\\d+")
	reRaw := regexp.MustCompile(`\d+`)
	actual4 := map[string]any{
		"dot_match":        regexp.MustCompile(`^a.c$`).MatchString("abc"),
		"dot_no_newline":   regexp.MustCompile(`^a.c$`).MatchString("a\nc"),
		"star_zero":        regexp.MustCompile(`^ab*c$`).MatchString("ac"),
		"plus_one_or_more": regexp.MustCompile(`^ab+c$`).MatchString("abbc"),
		"question_opt":     regexp.MustCompile(`^colou?r$`).MatchString("color"),
		"word_class":       regexp.MustCompile(`^\w+$`).MatchString("go_122"),
		"char_set":         regexp.MustCompile(`^[abc]+$`).MatchString("cab"),
		"escape_equiv":     reQuoted.FindString("v22") == reRaw.FindString("v22") && reRaw.FindString("v22") == "22",
	}
	expected4 := map[string]any{
		"dot_match":        true,
		"dot_no_newline":   false,
		"star_zero":        true,
		"plus_one_or_more": true,
		"question_opt":     true,
		"word_class":       true,
		"char_set":         true,
		"escape_equiv":     true,
	}
	cases = append(cases, makeCase(
		"regex_metacharacters_and_escaping",
		"核对常用正则元字符(. * + ? \\d \\w \\s [] ^ $)及双引号双反斜杠与反引号原始字符串等价性",
		expected4, actual4,
	))

	report := Report{
		Version: fmt.Sprintf("%s %s/%s", runtime.Version(), runtime.GOOS, runtime.GOARCH),
		Cases:   cases,
	}
	enc := json.NewEncoder(os.Stdout)
	enc.SetEscapeHTML(false)
	enc.SetIndent("", "  ")
	if err := enc.Encode(report); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
本例需在 本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。

入口文件:projects/go-regex-lab/explore_regex.go

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore_regex.go,或下载右侧课程工程包。
  2. 确认本地已准备 本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Go

课程关联工程包(登记关联33章) · 含当前章节或实例 · mbskycom202612a1159.zip

下载课程关联工程包:Go

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1183.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习