gpt4 book ai didi

正则表达式结束修饰符不在 Go 程序中返回结果

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

我有一个简单的 Go 程序来帮助学习正则表达式。它在无限循环中运行并有 2 个 channel ,一个用于提供输入(输入包含正则表达式模式和主题),第二个 channel 提供输出。

usage: main.exe (cat)+ catcatdog

但是代码中可能有问题,因为我似乎无法使用 $ 修饰符获得任何结果。

例如,我希望输出“cat”

main.exe cat$ cat\ndog

但收到零结果。

代码:

package main

import (
"fmt"
"regexp"
"bufio"
"os"
"strings"
)

type RegexRequest struct {
regex string
subject string
}

func main() {
regexRequests := make(chan *RegexRequest)
defer close(regexRequests)

regexAnswers, err := createResolver(regexRequests)
defer close(regexAnswers)
if(err != nil) { // TODO: Panics when exited via ctrl+c
panic(err)
}

interact(regexRequests, regexAnswers)
}

func interact(regexRequests chan *RegexRequest, regexAnswers chan []string) {
for {
fmt.Println("Enter regex and subject: ")
reader := bufio.NewReader(os.Stdin)

line, err := reader.ReadString('\n')
if(err != nil) {
panic(err)
}

regAndString := strings.SplitN(line, " ", 2);
if len(regAndString) != 2 {
fmt.Println("Invalid input, expected [regex][space][subject]")
continue
}

regexRequests <- &RegexRequest{ regAndString[0], regAndString[1] }
result := <- regexAnswers
var filteredResult []string
for _, element := range result {
if(element != "") {
filteredResult = append(filteredResult, element)
} else {
filteredResult = append(filteredResult, "EMPTY");
}
}

fmt.Println(strings.Join(filteredResult, " "))
}
}

func createResolver(inputChan chan *RegexRequest)(outputChan chan []string, err error) {
if(cap(inputChan) > 0) {
return nil, fmt.Errorf("Expected an unbuffered channel")
}

outputChan = make(chan []string)
err = nil

go func() {
for {
var regReq *RegexRequest= (<- inputChan);
var regex *regexp.Regexp = regexp.MustCompile(regReq.regex)
outputChan <- regex.FindAllString(regReq.subject, -1)
}
}()

return
}

最佳答案

检查您的 regex 模式。例如,

Enter regex and subject: 
cat$ cat\ndog

Enter regex and subject:
^cat cat\ndog
cat

关于正则表达式结束修饰符不在 Go 程序中返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16626366/

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