正则表达式在Go中不起作用

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

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 (
	&quot;fmt&quot;
	&quot;regexp&quot;
)

func main() {
	var a string = &quot;parameter=0xFF&quot;
	var regex string = &quot;^.+=\b0x[A-F][A-F]\b$&quot;
	result,err := regexp.MatchString(regex, a)
	fmt.Println(result, err)
}
// output: false &lt;nil&gt;

This seems to work OK in python

import re

p = re.compile(r&quot;^.+=\b0x[A-F][A-F]\b$&quot;)
m = p.match(&quot;parameter=0xFF&quot;)
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 &lt;anything&gt;=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 = &quot;^.+=\\b0x[A-F][A-F]\\b$&quot;

But in fact the \b (word boundaries) appear to be useless in your expression.

It works without them :

var regex string = &quot;^.+=0x[A-F][A-F]$&quot;

Demonstration

huangapple
  • 本文由 发表于 2013年1月6日 23:41:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/14183704.html
匿名

发表评论

匿名网友

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

确定