Golang Go语言中求一个正则表达式写法

一个目录下有很多 .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")
			}
		})
	}
}

求告知正确的写法。


Golang Go语言中求一个正则表达式写法

更多关于Golang Go语言中求一个正则表达式写法的实战教程也可以访问 https://www.itying.com/category-94-b0.html

10 回复

哈哈哈能不能把字符串反转之后不匹配 gol.1.这样的文件呢😁

更多关于Golang Go语言中求一个正则表达式写法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


字符串反转一下就行了

既然标准库不支持 Negative look-ahead 那就找个支持的开源库不就完事了。
https://github.com/dlclark/regexp2#compare-regexp-and-regexp2

.*([^1]|…{2,}).log$
--------------------------
当然,用正则表达式来解决这个问题非常蠢,直接截取文件名最后 6 个字符,如果等于 [.1.log] 直接不匹配就行了,两行就能搞定。

if filename[-6:] == ‘.1.log’:
continue

这样不就行了吗:
strings.HasSuffix(filename, “.1.log”)

换个思路。

如果只有 xx.log xx.2022-04-01.log 这两种形式,那就:
^[^.]+(?:.\d{4}-\d{2}-\d{2})?.log$

如果只需排除中间是纯数字,那就:
^[^.]+(?:…[^\d.]+.)?.log$

以上 ecmascript 正则,不懂 golang

logagent 采集目录打开的日志文件 lsof +d /path

path/filepath.Match 函数了解一下

用一个支持 look-ahead 的库

在Go语言中,使用正则表达式通常依赖于regexp标准库。要编写一个正则表达式,首先需要明确你要匹配的模式。下面是一个基本的例子和解释,帮助你入门。

假设你想匹配一个电子邮件地址,可以使用以下正则表达式:

`[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}`

这个正则表达式的大致含义是:

  • [a-zA-Z0-9._%+-]+ 匹配一个或多个字母、数字、点(.)、下划线(_)、百分号(%)、加号(+)或减号(-)。
  • @ 匹配字符“@”。
  • [a-zA-Z0-9.-]+ 匹配一个或多个字母、数字、点(.)或减号(-)。
  • \. 匹配点(.)字符(在正则表达式中点是一个特殊字符,表示任意字符,所以需要用\进行转义)。
  • [a-zA-Z]{2,} 匹配两个或更多字母(表示顶级域名)。

在Go语言中使用这个正则表达式的代码如下:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    re := regexp.MustCompile(`[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}`)
    fmt.Println(re.MatchString("example@example.com")) // 输出: true
}

这段代码会输出true,因为example@example.com符合我们定义的正则表达式模式。根据具体需求,你可以调整正则表达式的写法。

回到顶部