gpt4 book ai didi

regex - golang 正则表达式 ReplaceAllString

转载 作者:IT王子 更新时间:2023-10-29 01:38:26 30 4
gpt4 key购买 nike

我正在用 Go 编程语言编写一个聊天机器人程序。在此函数中,它读取用户字符串以检查正则表达式,然后删除该表达式并在找到时替换为另一个字符串。它成功找到匹配项,但不会将其附加到字符串

input = "I am feeling happy"
pattern2 := []string{`.*i am.*`, `.*I AM.*`, `.*I'm.*`, `.*i'm.*`, `.*im.*`, `.*I am.*`}

// loop through pattern2 array
//if pattern is found extract substring
//set response

for _, checkPattern := range pattern2 {
re := regexp.MustCompile(checkPattern)
if re.MatchString(input) {
match := re.ReplaceAllString(input, "How do you know you are $1 ?")
response = "output : " + match
return response
} //if re.MatchString
} //for pattern2

我的响应输出是“你怎么知道你是”

我的预期输出“你怎么知道你感到快乐”

最佳答案

您实际上可以重写正则表达式以避免循环。以下是@mypetlion 所谈论内容的说明:

package main

import (
"fmt"
"regexp"
)

func main() {
input := "I AM feeling happy"
re := regexp.MustCompile("(?i)(i[' a]*m) (.*)")
if re.MatchString(input) {
match := re.ReplaceAllString(input, "How do you know you are $2?")
fmt.Println("output: " + match)
} else {
fmt.Println("There is no match")
}
}

表达式 (?i)(i[' a]*m) (.*) 基本上捕获字符串中存在的两组字符。第一组是I am的各种格式。这也适用于其他变体。第二个匹配 I am 之后的剩余字符串。请注意,我们使用 (?i) 使正则表达式不区分大小写。

一旦我们编译了表达式,我们就会继续使用来自第二组 的匹配字符串作为我们的替换。

对于 I am 的所有变体,您应该得到以下信息:

output: How do you know you are feeling happy?

希望对您有所帮助。

关于regex - golang 正则表达式 ReplaceAllString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47319703/

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