【问题标题】:Catch by pattern except strings which ends with two special characters in a row除以连续两个特殊字符结尾的字符串外,按模式捕获
【发布时间】:2022-01-03 12:10:57
【问题描述】:

我正在尝试创建一个通过特定模式捕获字符串的 Go 正则表达式,除了以连续 2 个特殊字符结尾的字符串,并且不想使用前瞻,这可能吗?

这是我目前的模式(?:[a-zA-Z]+.)+\.[a-zA-Z]{2,}

例如,给这个字符串:test.testing.com. test2.net.*

我想赶上test.testing.com不是 test2.net

【问题讨论】:

    标签: regex go


    【解决方案1】:

    你可以用

    捕捉那部分
    \b([a-zA-Z]+(?:\.[a-zA-Z]+)*)\b(?:.?$|[[:punct:]][^[:punct:]]|[^[:punct:]][[:punct:]])
    

    请参阅regex demo详情

    • \b - 单词边界
    • ([a-zA-Z]+(?:\.[a-zA-Z]+)*)
    • \b - 单词边界
    • (?: - 非捕获组的开始:
      • .?$ - 任何可选的单个字符(换行符除外)和字符串结尾
      • | - 或
      • [[:punct:]][^[:punct:]] - 一个标点符号和一个非标点符号
      • | - 或
      • [^[:punct:]][[:punct:]] - 非标点符号和标点符号字符
    • ) - 非捕获组结束。

    Go demo

    package main
    
    import (
        "fmt"
        "regexp"
    )
    
    func main() {
        markdownRegex := regexp.MustCompile(`\b([a-zA-Z]+(?:\.[a-zA-Z]+)*)\b(?:.?$|[[:punct:]][^[:punct:]]|[^[:punct:]][[:punct:]])`)
        str := `test.testing.com. test2.net.*`
        for _, result := range markdownRegex.FindAllStringSubmatch(str, -1) {
            fmt.Printf("%s\n", result[1])
        }
    }
    // => test.testing.com
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-16
      • 1970-01-01
      • 2020-04-10
      • 1970-01-01
      • 2014-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多