英文:
Escaping parentheses in Go regexp
问题
我正在尝试在Go中对字符串运行以下正则表达式:
\(([0-9]+),([0-9.]+),(?:$([0-9]+))\)
但是我一直收到错误消息unknown escape sequence: (
我要运行它的字符串是(1,53.38,$45) (2,88.62,$98) (3,78.48,$3) (4,72.30,$76) (5,30.18,$9) (6,46.34,$48)
所以我的问题是,如何在Go的正则表达式中转义括号?
英文:
I am tying to run the following regular expression on a string in Go
\(([0-9]+),([0-9.]+),(?:$([0-9]+))\)
but I keep getting the error unknown escape sequence: (
the string that I'm running it on is (1,53.38,$45) (2,88.62,$98) (3,78.48,$3) (4,72.30,$76) (5,30.18,$9) (6,46.34,$48)
So my question is, how do you escape parentheses in Go's regexp?
答案1
得分: 15
你需要转义反斜杠,因为\(
不是一个有效的转义序列。
"\\(([0-9]+),([0-9.]+),(?:$([0-9]+))\\)"
更常见的做法是使用反引号来表示字符串字面量而无需转义:
`\(([0-9]+),([0-9.]+),(?:$([0-9]+))\)`
英文:
You need to escape the backslashes, because \(
isn't a valid excape sequence.
"\\(([0-9]+),([0-9.]+),(?:$([0-9]+))\\)"
More commonly you would use backticks for string literals without escaping:
`\(([0-9]+),([0-9.]+),(?:$([0-9]+))\)`
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论