doufa5001 2011-07-21 03:16
浏览 139
已采纳

Go中的“未知转义序列”错误

I have the following function written in Go. The idea is the function has a string passed to it and returns the first IPv4 IP address found. If no IP address is found, an empty string is returned.

func parseIp(checkIpBody string) string {
    reg, err := regexp.Compile("[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+")
    if err == nil {
        return ""
    }   
    return reg.FindString(checkIpBody)
}

The compile-time error I'm getting is

unknown escape sequence: .

How can I tell Go that the '.' is the actual character I'm looking for? I thought escaping it would do the trick, but apparently I'm wrong.

  • 写回答

2条回答 默认 最新

  • donglu3184 2011-07-21 03:19
    关注

    The \ backslash isn't being interpreted by the regex parser, it's being interpreted in the string literal. You should escape the backslash again:

    regexp.Compile("[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+")
    

    A string quoted with " double-quote characters is known as an "interpreted string literal" in Go. Interpreted string literals are like string literals in most languages: \ backslash characters aren't included literally, they're used to give special meaning to the next character. The source must include \\ two backslashes in a row to obtain an a single backslash character in the parsed value.

    Go has another alternative which can be useful when writing string literals for regular expressions: a "raw string literal" is quoted by ` backtick characters. There are no special characters in a raw string literal, so as long as your pattern doesn't include a backtick you can use this syntax without escaping anything:

    regexp.Compile(`[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+`)
    

    These are described in the "String literals" section of the Go spec.

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

报告相同问题?

悬赏问题

  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错