doudun3910 2018-07-27 13:00
浏览 418
已采纳

正则表达式以匹配不同的分隔符

I need to get string between two delimters. And these pair of delimters are different. Here is my text:

[2018.07.10 00:30:03:640][TraceID: 8HRWSI105YVO91]->StartExecuteTask\35
[2018.07.10 00:30:18:585][TraceID: 8707HFH7NR6307]->RequestInfo\27
[2018.07.10 00:30:18:585][TraceID: 8707HFH7NR6307]->RequestExecuteEnd\16
[2018.07.10 00:30:18:585][TraceID: 8707HFH7NR6307]->OutgoingData\26651
[2018.07.10 00:31:16:773][TraceID: G8EM5LANBPC32H]->CheckUserInfo\141

I need to get time, traceid and requset type (after -> before \{d} )

And here is my regexp:

[\[|\->](.*?)[\\|\]]

What i get:

2018.07.10 00:30:03:640   TraceID: 8HRWSI105YVO91  >StartExecuteTask
2018.07.10 00:30:18:585   TraceID: 8707HFH7NR6307  >RequestInfo

I can't remove the > from last match. Or maybe whole regexp is wrong?

  • 写回答

1条回答 默认 最新

  • doutang7661 2018-07-27 13:02
    关注

    You may use

    (?:\[|->)(.*?)[\\\]]
    

    See the regex demo

    In Go, declare as

    var re = regexp.MustCompile(`(?:\[|->)(.*?)[\\\]]`)
    

    Details

    • (?:\[|->) - a non-capturing group that matches either [ char or -> substring
    • (.*?) - Group 1: any 0+ chars, other than line break chars, as few as possible
    • [\\\]] - a \ or ] char.

    Demo:

    package main
    
    import (
        "regexp"
        "fmt"
    )
    
    func main() {
        var re = regexp.MustCompile(`(?:\[|->)(.*?)[\\\]]`)
        var str = `[2018.07.10 00:30:03:640][TraceID: 8HRWSI105YVO91]->StartExecuteTask\35`
    
        for _, match := range re.FindAllStringSubmatch(str, -1) {
            fmt.Println(match[1])
        }   
    }
    

    Output:

    2018.07.10 00:30:03:640
    TraceID: 8HRWSI105YVO91
    StartExecuteTask
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大