douzai1074 2014-03-09 12:35
浏览 61
已采纳

如何在Golang中编写简单的正则表达式?

I am trying to write regexp that returns the substring for string that begins with dot and until first space. But I am new in regular expressions, so I tried something like that and it doesn't work at all:

package main

import "fmt"
import "regexp"

func main() {
    re := regexp.MustCompile("\\.* ")
    fmt.Printf(re.FindString(".d 1000=11,12")) // Must return d
    fmt.Printf(re.FindString("e 2000=11"))     // Must return nothing or ""
    fmt.Printf(re.FindString(".e2000=11"))     // Must return nothing or ""
}

this code just white 3 white space in golang. What I am doing wrong?

  • 写回答

2条回答 默认 最新

  • duanchi8112 2014-03-09 14:30
    关注

    While * is the wildcard in glob matching, it's not the wildcard in regex. In regex, . is the wildcard and * means repetition of 0 or more times. You probably want:

    re := regexp.MustCompile("\\..* ")
    

    go playground

    But you might notice that it's also returning the dot and space. You can use FindStringSubmatch and use a capture group to fix this, and you can use backsticks so that you don't have to double escape things:

    re := regexp.MustCompile(`\.(.*) `)
    match := re.FindStringSubmatch(".d 1000=11,12")
    if len(match) != 0 {fmt.Printf("1. %s
    ", match[1])}
    

    go playground

    Though I would prefer using \S* (matches non-space characters) instead of .* to get this match, since it'll reduce the possible backtracking:

    re := regexp.MustCompile(`\.(\S*) `)
    

    go playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Matlab问题解答有两个问题
  • ¥50 Oracle Kubernetes服务器集群主节点无法访问,工作节点可以访问
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架
  • ¥15 有关sql server business intellige安装,包括SSDT、SSMS。
  • ¥15 stm32的can接口不能收发数据
  • ¥15 目标检测算法移植到arm开发板
  • ¥15 利用JD51设计温度报警系统
  • ¥15 快手联盟怎么快速的跑出建立模型