golang 解析 Apache Ant 样式路径

golang 解析 Apache Ant 样式路径

Apache Ant 样式路径通配符

  • ? 匹配任何单字符
  • * 匹配0或者任意数量的字符,不包含"/"
  • ** 匹配0或者更多的目录,包含"/"

匹配示例

  • path/**/*.txt: 匹配 path 目录及其子目录下所有以 .txt 结尾的文件
    例如:

    1
    2
    3
    4
    path/file1.txt
    path/file2.txt
    path/to/subdirectory/file.txt
    path/subdirectory/file3.txt
  • path/**/file?.txt: 匹配 path 目录及其子目录下以 file 开头,后跟任意一个字符,然后以 .txt 结尾的文件
    例如

    1
    2
    3
    4
    path/file1.txt
    path/fileA.txt
    path/to/subdirectory/fileX.txt
    path/subdirectory/file3.txt

github.com/bmatcuk/doublestar/v3

github.com/bmatcuk/doublestar/v3 是一个 Golang 的第三方库,用于支持通配符模式的文件路径匹配。它提供了强大的递归通配符匹配功能,适用于处理 Apache Ant 表达式.

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import (
"fmt"
"github.com/bmatcuk/doublestar/v3"
)

func main() {
// 定义 Apache Ant 表达式
antExpression := "**/*.txt"

// 匹配文件路径
filePath := "path/to/file.txt"
isMatch, err := doublestar.Match(antExpression, filePath)
if err != nil {
fmt.Println("匹配失败:", err)
return
}

// 输出结果
if isMatch {
fmt.Println("Expression matched")
} else {
fmt.Println("Expression not matched")
}
}