regex - 如何制作一个正则表达式来匹配模式之间带有随机点的字符串?

标签 regex go

我想将一个字符串与一部分模式进行比较,看看是否存在点之间的模式变化:
functin看起来像这样:

patterns := []string{"cat", "fish", "dog"}
func HasBadPattern(word string, patterns []string) bool {       
    for _, p := range patterns {
        myRegex, err := regexp.Compile(p)
        if err != nil {
            log.Println(err)
        }
        //Don't know how to perpare the wordToCompile ?
        matched := myRegex.FindString(wordToCompile)
        if len(matched) > 0 {
            return true
            break
        }
    }
    return false
}
结果应该是这样的:
HasBadPattern("c.at", patterns) //true
HasBadPattern("c.a.t", patterns) //true
HasBadPattern("c.a..t", patterns) //true
HasBadPattern("fis.h", patterns) //true
HasBadPattern("catfish", patterns) //false
HasBadPattern("here is the cat.", patterns) //false
HasBadPattern("cat is on the mat.", patterns) //false
HasBadPattern("cat.fish", patterns) //false
我的问题是如何准备ocht_code以便为字符之间的点编译而不会产生误报。
Here is the playground scaffolding

最佳答案

看来您基本上是想在字符串的字符之间插入\.*(零个或多个句点)。例如,"c.at""c.a.t""c.a..t"都由表达式^\.*c\.*a\.*t\.*$匹配。
可以使用类似(不是最有效的...)的函数来完成:

func randomDots(word string) string {
    dots := "\\.*"
    expression := fmt.Sprintf("^%s", dots)

    for i := range word {
        expression += fmt.Sprintf("%c%s", word[i], dots)
    }
    expression += "$"
    return expression
}
然后,您可以将HasBadPattern更改为:
func HasBadPattern(word string, patterns []string) bool {
    for _, p := range patterns {
        expression := randomDots(p)
        myRegex, _ := regexp.Compile(expression)
        matched := myRegex.FindString(word)
        if len(matched) > 0 {
            return true
        }
    }
    return false
}

关于regex - 如何制作一个正则表达式来匹配模式之间带有随机点的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62913384/

相关文章:

java - 如何在Java中实现正则表达式

regex - 使用正则表达式的条件子表达式替换

java - 如何用 Math Ml 标签包围数字?

go - time.Location()返回“Local”,即使/etc/localtime是正确的

json - 是否可以绑定(bind)到自定义结构类型的 map 对象?

javascript - 将带有方括号的字符串转换为方括号内容合并的列表

go - 为什么 GAE 数据存储不支持简单的结构字段类型?

http - 将 Go 网络服务器部署到 Google 计算引擎

mongodb - 复合文字使用无键字段

正则表达式允许数字和一个点