gpt4 book ai didi

regex - Golang 正则表达式总是返回 false?

转载 作者:数据小太阳 更新时间:2023-10-29 03:03:26 25 4
gpt4 key购买 nike

我正在接受用户输入(正则表达式),并检查文件的给定行是否与它匹配。如果匹配(行的 ID),我将返回一些 ID,仅此而已。但是,似乎我的 match 总是返回 false?但是,有趣的是,如果我抛出一个通配符 .*,程序的执行时间将比特定的正则表达式要长得多。所以,一定有什么事情发生了——为什么它总是返回 false?

示例代码:

func main() {

// User input from command line
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter regexp: ")
userRegexp, _ := reader.ReadString('\n')

// List all .html files in static dir
files, err := filepath.Glob("static/*.html")
if err != nil {
log.Fatal(err)
}

// Empty array of int64's to be returned with matching results
var lineIdArr []int64

for _, file := range files {
htmlFile, _ := os.Open(file)
fscanner := bufio.NewScanner(htmlFile)

// Loop over each line
for fscanner.Scan() {

line := fscanner.Text()

match := matchLineByValue(userRegexp, line) // This is always false?

// ID is always the first item. Seperate by ":" and cast it to int64.
lineIdStr := line[:strings.IndexByte(line, ':')]
lineIdInt, err := strconv.ParseInt(lineIdStr, 10, 64)

if err != nil {
panic(err)
}

// If matched, append ID to lineIdArr
if match {
lineIdArr = append(lineIdArr, lineIdInt)
}
}
}
fmt.Println("Return array: ", lineIdArr)
fmt.Println("Using regular expression: ", userRegexp)
}

func matchLineByValue(re string, s string) bool {
return regexp.MustCompile(re).MatchString(s)
}

regexp.MustCompile(re).MatchString(s) 不是根据用户输入构建正则表达式并将其匹配到整行的正确方法吗?

它匹配的字符串很长(基本上是一个完整的html文件),会不会出现问题?

最佳答案

调用 userRegexp, _ := reader.ReadString('\n') 返回一个带有尾随换行符的字符串。修剪换行符:

 userRegexp, err := reader.ReadString('\n')
if err != nil {
// handle error
}
userRegexp = userRegexp[:len(userRegexp)-1]

下面是一些其他改进的代码(编译正则表达式一次,使用扫描器字节):

// User input from command line
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter regexp: ")
userRegexp, err := reader.ReadString('\n')
if err != nil {
log.Fatal(err)
}
userRegexp = userRegexp[:len(userRegexp)-1]
re, err := regexp.Compile(userRegexp)
if err != nil {
log.Fatal(err)
}

// List all .html files in static dir
files, err := filepath.Glob("static/*.html")
if err != nil {
log.Fatal(err)
}

// Empty array of int64's to be returned with matching results
var lineIdArr []int64

for _, file := range files {
htmlFile, _ := os.Open(file)
fscanner := bufio.NewScanner(htmlFile)
// Loop over each line
for fscanner.Scan() {
line := fscanner.Bytes()
if !re.Match(line) {
continue
}
lineIdStr := line[:bytes.IndexByte(line, ':')]
lineIdInt, err := strconv.ParseInt(string(lineIdStr), 10, 64)
if err != nil {
log.Fatal(err)
}
lineIdArr = append(lineIdArr, lineIdInt)
}
}
fmt.Println("Return array: ", lineIdArr)
fmt.Println("Using regular expression: ", userRegexp)

关于regex - Golang 正则表达式总是返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49351605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com