regex - golang正则表达式ReplaceAllString

标签 regex go chatbot

我正在用 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/

相关文章:

java - 我可以使用正则表达式或其他方式更快地执行此操作吗?

go - 从bep_0009 [golang]失败的对等节点下载元数据

inheritance - Golang : when typecasting child struct to parent struct, 子结构信息丢失?

azure - 是否可以在没有azure平台的情况下创建聊天机器人(使用microsoft bot平台和luis)

c# - Bot Framework 搞乱了对话框状态

machine-learning - 机智.ai : how does it identify intent and classifies entities from user expressions

c# - 使用静态 Regex.IsMatch 与创建 Regex 实例

c# - .NET 中不同运行时间执行的相同正则表达式

r - str_extract 仅捕获重复出现的关键字的一个实例

python - gocv 中是否有类似 python 中的 np.where() 的函数?