Escaping parentheses in Go regexp

huangapple go评论90阅读模式
英文:

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

huangapple
  • 本文由 发表于 2016年2月4日 00:56:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/35183103.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定