“未知转义序列” Go中的错误 [英] "Unknown escape sequence" error in Go

查看:835
本文介绍了“未知转义序列” Go中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Go编写了以下函数。这个想法是函数有一个字符串传递给它并返回找到的第一个IPv4 IP地址。

  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)
}

我得到的编译时错误是


未知的转义序列:。 p>

我该如何告诉Go '。'是实际的字符I'米寻找?我认为转义它会做到这一点,但显然我错了。 反斜杠不被正则表达式解析器解释,它在字符串文字中被解释。你应该再次避开反斜线:



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

双引号字符引用的字符串称为解释的字符串字面,在大多数语言中,解释字符串文字就像字符串文字: \ 反斜线字符不是字面意义上的,它们用于给下一个字符赋予特殊含义字符,源代码必须在一行中包含 \\ 两个反斜杠,以获得解析值中的单个反斜杠字符。



由于 Evan Shaw在评论中指出,Go有另一种选择这在为正则表达式编写字符串文字时很有用,原始字符串文字由<引用code>`反引号字符在原始字符串文本中没有特殊字符,所以只要你的模式不包含反引号,你可以使用这个语法而不会转义任何东西:

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

这是如 Go spec 的字符串文字部分所述。


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.

解决方案

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 included \\ two backslashes in a row to obtain an a single backslash character in the parsed value.

As Evan Shaw pointed out in the comments, 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]+`)

This is described in the "String literals" section of the Go spec.

这篇关于“未知转义序列” Go中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆