Golang SplitAfter for Regexp类型

时间:2016-12-23 12:59:14

标签: regex go

在golang val actorRef = ??? //setup the ref to remote UpperActor /**Query the Actor*/ val dispatchByteString : (ByteString) => Future[String] = (byteString : ByteString) => (actorRef ? byteString).mapTo[String] val parallelism = 10 // should match your Actor's mailbox size /**Construct the Response Source.*/ val requestToSrc : (HttpRequest) => Source[ChunkStreamPart,_] = (_ : HttpRequest).entity .dataBytes .mapAsync(parallelism)(dispatchByteString) .map(ChunkStreamPart.apply) val contentType = ContentTypes.`text/plain(UTF-8)` val route = extractRequest { request => complete(HttpResponse(entity = Chunked(contentType, requestToSrc(request)))) } 方法中将特殊字符后的文本拆分成切片,但我没有找到Regexp类型在匹配后拆分文本的方法。有没有办法做到这一点?

示例:

strings.SplitAfter

2 个答案:

答案 0 :(得分:0)

Regexp类型本身没有一种方法可以完全做到这一点,但编写一个能够根据Regexp功能实现您的要求的函数非常简单:

func SplitAfter(s string, re *regexp.Regexp) []string {
    var (
        r []string
        p int
    )
    is := re.FindAllStringIndex(s, -1)
    if is == nil {
        return append(r, s)
    }
    for _, i := range is {
        r = append(r, s[p:i[1]])
        p = i[1]
    }
    return append(r, s[p:])
}

Here我离开了一个程序来玩它。

答案 1 :(得分:0)

首先,您的正则表达式 "." 对于 splitAfter 函数是错误的。您需要数字后跟值 ".",因此正则表达式为:"[1-9]"

您正在查看的函数可能如下所示:

func splitAfter(s string, re *regexp.Regexp) (r []string) {
    re.ReplaceAllStringFunc(s, func(x string) string {
        s = strings.Replace(s,x,"::"+x,-1)
        return s
    })
    for _, x := range strings.Split(s,"::") {
        if x != "" {
            r = append(r, x)
        }
    }
    return
}

比:

    fmt.Println(splitAfter("healthyRecordsMetric",regexp.MustCompile("[A-Z]")))
    fmt.Println(splitAfter("healthyrecordsMETetric",regexp.MustCompile("[A-Z]")))
    fmt.Println(splitAfter("HealthyHecord Hetrics",regexp.MustCompile("[A-Z]")))
    fmt.Println(splitAfter("healthy records metric",regexp.MustCompile("[A-Z]")))
    fmt.Println(splitAfter("1.2.3.4.5.6.7.8.9",regexp.MustCompile("[1-9]")))

[Healthy Records Metric]
[healthy Records Metric]
[healthyrecords M E Tetric]
[Healthy Hecord  Hetrics]
[healthy records metric]
[1. 2. 3. 4. 5. 6. 7. 8. 9]


祝你好运!