You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go RE2正则优化:过滤含数字子串(s3除外)

问题:调整Go RE2正则表达式实现特定字符串处理需求

现有Go RE2正则表达式[^-]+-[^-]+可截取字符串中前两个连字符分隔的内容(例如将bob-marley-bla-bla转换为bob-marley),现需增强该正则,要求移除所有包含数字的子串(如67srer),但子串为s3时除外。

示例效果

bob-7878dccdf-marley => bob-marley 
8sdfhsdf-bob-marley => bob-marley 
s3-bob-marley => s3-bob-marley 
bob-666777-marley => bob-marley
s3-sd8s7dfx-bob-marley-9d8f9 => s3-bob-marley
hgfs889899-bob-marley => bob-marley 
bob-45345sdfsfd-marley => bob-marley 
bob-marley-8s7d8f7s8df => bob-marley

待修改的Go代码

package main

import (
    "fmt"
    "regexp"
    "strings"
)

func main() {
    // Define the regular expression pattern to match sequences of characters that are not 's3' or '-'
    pattern := regexp.MustCompile(`[^-]+-[^-]+`)

    // Test cases
    testCases := []string{
        "bob-7878dccdf-marley",
        "bob-666777-marley",
        "8sdfhsdf-bob-marley",
        "s3-bob-marley",
        "s3-sd8s7dfx-bob-marley-9d8f9",
        "hgfs889899-bob-marley",
        "bob-45345sdfsfd-marley",
        "bob-marley-8s7d8f7s8df",
    }

    for _, testCase := range testCases {
        // Remove unwanted characters
        result := pattern.FindAllString(testCase, -1)
        // Join the matched sequences
        resultStr := strings.Join(result, "")
        fmt.Printf("%s is changed to %s\n", testCase, resultStr)
    }
}

解决方案

正则表达式(适用于Promtail/Go RE2)

要实现需求,可使用以下正则直接捕获目标内容,匹配后替换为$1-$2即可:

^(?:(?:(?!s3)[^-]*\d[^-]*-)*)?(s3|[^-\d]+)(?:-(?:(?!s3)[^-]*\d[^-]*-)*)?(s3|[^-\d]+)

该正则会自动跳过所有包含数字且非s3的子串,捕获前两个符合要求的有效子串。

修改后的Go代码验证

如果用Go代码实现,更清晰的方式是先分割字符串、过滤有效子串,再取前两个拼接,可读性更强:

package main

import (
    "fmt"
    "regexp"
    "strings"
)

func main() {
    // 匹配有效子串:要么是s3,要么不含任何数字
    validSubstr := regexp.MustCompile(`^(s3|[^\d]+)$`)

    testCases := []string{
        "bob-7878dccdf-marley",
        "bob-666777-marley",
        "8sdfhsdf-bob-marley",
        "s3-bob-marley",
        "s3-sd8s7dfx-bob-marley-9d8f9",
        "hgfs889899-bob-marley",
        "bob-45345sdfsfd-marley",
        "bob-marley-8s7d8f7s8df",
    }

    for _, testCase := range testCases {
        // 按连字符分割字符串
        parts := strings.Split(testCase, "-")
        var validParts []string
        // 过滤并保留前两个有效子串
        for _, part := range parts {
            if validSubstr.MatchString(part) {
                validParts = append(validParts, part)
                if len(validParts) == 2 {
                    break
                }
            }
        }
        // 拼接结果
        resultStr := strings.Join(validParts, "-")
        fmt.Printf("%s is changed to %s\n", testCase, resultStr)
    }
}

运行该代码会输出完全符合示例要求的结果。

内容的提问来源于stack exchange,提问作者akshaykrjain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 09:09:53