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

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

问题描述

我有以下用 Go 编写的函数.这个想法是函数有一个字符串传递给它并返回找到的第一个 IPv4 IP 地址.如果没有找到 IP 地址,则返回一个空字符串.

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

我得到的编译时错误是

未知的转义序列:.

我如何告诉 Go '.' 是我正在寻找的实际字符?我认为逃避它会成功,但显然我错了.

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

Go 有另一种替代方法,在为正则表达式编写字符串文字时非常有用:原始 字符串文字";由 ` 反引号字符引用.原始字符串文字中没有特殊字符,因此只要您的模式不包含反引号,您就可以使用此语法而无需转义任何内容:

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]+`)

这些在字符串文字"中进行了描述.Go 规范的部分.

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

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