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

我用 Go 编写了以下函数。其思想是函数有一个字符串传递给它,并返回找到的第一个 IPv4 IP 地址。如果没有找到 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)
}

我得到的编译时错误是

未知的转义序列。

我怎样才能告诉 Go,'.'就是我正在寻找的字符?我以为逃出去就能解决问题,但显然我错了。

61657 次浏览

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.

IPv4 address (accurate capture)

Matches 0.0.0.0 through 255.255.255.255

Use this regex to match IP numbers with accurracy.

Each of the 4 numbers is stored into a capturing group, so you can access them for further processing.

"(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])"