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