【发布时间】:2018-05-01 13:47:10
【问题描述】:
我在用正则表达式替换单词 "you're" 时遇到问题。
所有其他单词都在正确更改,只是单词 “you're”。 我认为它不是在撇号之后解析。
我必须将单词 "you" 替换为 "I" 和 "you're" 替换为 "I'米”。 它将 "you" 更改为 "I" 但 "you're" 变为 "I're"因为它没有超过撇号,并且出于某种原因它认为这是单词的结尾。我必须以某种方式逃避撇号。
请参阅下面的相关代码。
package main
import (
"fmt"
"math/rand"
"regexp"
"strings"
"time"
)
//Function ElizaResponse to take in and return a string
func ElizaResponse(str string) string {
// replace := "How do you know you are"
/*Regex MatchString function with isolation of the word "father"
*with a boundry ignore case regex command.
*/
if matched, _ := regexp.MatchString(`(?i)\bfather\b`, str);
//Condition to replace the original string if it has the word "father"
matched {
return "Why don’t you tell me more about your father?"
}
r1 := regexp.MustCompile(`(?i)\bI'?\s*a?m\b`)
//Match the words "I am" and capture for replacement
matched := r1.MatchString(str)
//condition if "I am" is matched
if matched {
capturedString := r1.ReplaceAllString(str, "$1")
boundaries := regexp.MustCompile(`\b`)
tokens := boundaries.Split(capturedString, -1)
// List the reflections.
reflections := [][]string{
{`I`, `you`},
{`you're`, `I'm`},
{`your`, `my`},
{`me`, `you`},
{`you`, `I`},
{`my`, `your`},
}
// Loop through each token, reflecting it if there's a match.
for i, token := range tokens {
for _, reflection := range reflections {
if matched, _ := regexp.MatchString(reflection[0], token); matched {
tokens[i] = reflection[1]
break
}
}
}
// Put the tokens back together.
return strings.Join(tokens, ``)
}
//Get random number from the length of the array of random struct
//an array of strings for the random response
response := []string{"I’m not sure what you’re trying to say. Could you explain it to me?",
"How does that make you feel?",
"Why do you say that?"}
//Return a random index of the array
return response[rand.Intn(len(response))]
}
func main() {
rand.Seed(time.Now().UTC().UnixNano())
fmt.Println("Im supposed to just take what you're saying at face value?")
fmt.Println(ElizaResponse("Im supposed to just take what you're saying at face value?"))
}
【问题讨论】:
-
请注意,您的示例文本包含卷曲撇号,而您的正则表达式仅包含单引号(当您按单引号键时实际得到的结果没有某种“智能引号”功能在文字处理器中查找)。
-
注意
r1模式不包含任何捕获组,当您替换为$1时,您只需删除匹配项。所以,capturedString := r1.ReplaceAllString(str, "$1")=capturedString := r1.ReplaceAllString(str, "")。我知道这不是代码中最重要的部分,但请确保您了解它在做什么。 -
当我完成第一个问题时,我将替换它。它正在替换“我是,我是,我”,所有大小写都被忽略了。在我有你正确改变这个词之后,我有句子要连接到它。
-
好的,请参阅this demo。抱歉,我很着急,但你会明白要点的。
-
谢谢 Wiktor Stribiżew 这是一个很好的解决方案。我发现我只需要将正则表达式更改为边界变量。我会在下面发布我的解决方案。再次感谢!!
标签: regex go regex-group