一个目录下有很多 .log
的文件
xx.log xx.2022-04-01.log xx.1.log
需要排除 .1.log
这样的文件。
由于 go 不支持 Negative look-ahead 。不能用 (?!
func TestRegex2(t *testing.T) { r, err := regexp.Compile(`.*([^.]\D)\.log$`) if err != nil { t.Fatal(err) } cases := []struct { dest string match bool }{ {"/afafa/a.log", true}, {"/afafa/a_err.log", true}, {"/afafa/a_.log", true}, {"/afafa/a_3.log", true}, // 报错 {"/afafa/a_3.abc.log", true}, {"/afafa/a.1.log", false}, {"/afafa/a.2022.log", true}, // 报错 {"/afafa/a.2022-4-1.log", true}, // 报错 } for i := range cases { t.Run(cases[i].dest, func(t *testing.T) { if r.MatchString(cases[i].dest) != cases[i].match { t.Errorf("match not correct") } }) } }
求告知正确的写法。
![]() | 1 lozzow 2022-05-05 18:20:20 +08:00 哈哈哈能不能把字符串反转之后不匹配 gol.1.这样的文件呢 |
![]() | 2 ch2 2022-05-05 18:35:48 +08:00 字符串反转一下就行了 |
![]() | 3 AlisaDestiny 2022-05-05 18:37:12 +08:00 既然标准库不支持 Negative look-ahead 那就找个支持的开源库不就完事了。 https://github.com/dlclark/regexp2#compare-regexp-and-regexp2 |
4 AX5N 2022-05-05 18:59:07 +08:00 .*([^1]|\..{2,})\.log$ -------------------------- 当然,用正则表达式来解决这个问题非常蠢,直接截取文件名最后 6 个字符,如果等于 [.1.log] 直接不匹配就行了,两行就能搞定。 if filename[-6:] == '.1.log': continue |
![]() | 5 Dvel 2022-05-05 19:16:08 +08:00 这样不就行了吗: strings.HasSuffix(filename, ".1.log") |
6 darklights 2022-05-05 21:11:59 +08:00 换个思路。 如果只有 xx.log xx.2022-04-01.log 这两种形式,那就: ^[^.]+(?:\.\d{4}-\d{2}-\d{2})?\.log$ 如果只需排除中间是纯数字,那就: ^[^.]+(?:\..*[^\d.]+.*)?\.log$ 以上 ecmascript 正则,不懂 golang |
![]() | 7 ropon 2022-05-06 08:09:47 +08:00 via iPhone logagent 采集目录打开的日志文件 lsof +d /path |
![]() | 8 eudore 2022-05-06 09:15:07 +08:00 `path/filepath.Match` 函数了解一下 |
![]() | 9 cyjme 2022-05-06 10:42:58 +08:00 用一个支持 look-ahead 的库 |