英文:
Regular expression doesn't work in Go
问题
原谅我是一个正则表达式的业余爱好者,但我真的很困惑为什么这段代码在Go中不起作用。
package main
import (
"fmt"
"regexp"
)
func main() {
var a string = "parameter=0xFF"
var regex string = "^.+=\b0x[A-F][A-F]\b$"
result,err := regexp.MatchString(regex, a)
fmt.Println(result, err)
}
// 输出: false <nil>
这在Python中似乎可以正常工作。
import re
p = re.compile(r"^.+=\b0x[A-F][A-F]\b$")
m = p.match("parameter=0xFF")
if m is not None:
print m.group()
// 输出: parameter=0xFF
我只想匹配输入是否符合格式 <anything>=0x[A-F][A-F]
任何帮助将不胜感激。
英文:
forgive me for being a regex amateur but I'm really confused as to why this doesn't piece of code doesn't work in Go
package main
import (
"fmt"
"regexp"
)
func main() {
var a string = "parameter=0xFF"
var regex string = "^.+=\b0x[A-F][A-F]\b$"
result,err := regexp.MatchString(regex, a)
fmt.Println(result, err)
}
// output: false <nil>
This seems to work OK in python
import re
p = re.compile(r"^.+=\b0x[A-F][A-F]\b$")
m = p.match("parameter=0xFF")
if m is not None:
print m.group()
// output: parameter=0xFF
All I want to do is match whether the input is in the format <anything>=0x[A-F][A-F]
Any help would be appreciated
答案1
得分: 9
你尝试过使用原始字符串字面量(使用反引号而不是引号)吗?
像这样:
var regex string = `^.+=\b0x[A-F][A-F]\b$`
英文:
Have you tried using raw string literal (with back quote instead of quote)?
Like this:
var regex string = `^.+=\b0x[A-F][A-F]\b$`
答案2
得分: 5
你必须在解释性字符串字面值中转义\
:
var regex string = "^.+=\\b0x[A-F][A-F]\\b$"
但实际上,在你的表达式中,\b
(单词边界)似乎是无用的。
它们可以不用:
var regex string = "^.+=0x[A-F][A-F]$"
英文:
You must escape the \
in interpreted literal strings :
var regex string = "^.+=\\b0x[A-F][A-F]\\b$"
But in fact the \b
(word boundaries) appear to be useless in your expression.
It works without them :
var regex string = "^.+=0x[A-F][A-F]$"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论