How to use word boundry (\b) with regexp.MatchString() in go

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

How to use word boundry (\b) with regexp.MatchString() in go

问题

我正在使用regexp.matchString()函数来匹配正则表达式模式到我的字符串。为了找到精确匹配,我必须使用单词边界。例如,我想匹配"compute"但不匹配"computer"。问题是我的字符串中既有"compute"又有"computer"。所以我想使用单词边界。我尝试在几个在线的go-regex测试器中使用\b,它起作用了。然而,\b似乎在regexp.matchString()函数中不起作用。有人知道是否有替代\b的方法吗?或者我该如何获得期望的结果?

我的代码:

package main

import "fmt"
import "regexp"

func main() {
    fmt.Println("Hello, playground")
    brandName := "home;compute furniture;computer"
    filterVal := "(?i)compute\b"
    regexMatch, _ := regexp.MatchString(filterVal, brandName)
    fmt.Println(regexMatch)
}

当我使用\b时,这个函数返回false。请帮忙解决。

英文:

I am using a function regexp.matchString() to match regex pattern to my string. I have to use word boundary in order to find exact match. For example, I want to match "compute" but not "computer". The problem is my string will have both "compute" and "computer". So I want to use word boundary. I tried using \b in couple of online go-regex tester and it worked. However, \b does not seem to work for regexp.matchString() function. Does anyone know if there is an alternate to \b? or how can I get expected result?
My code

package main

import "fmt"
import "regexp"

func main() {
	fmt.Println("Hello, playground")
	brandName := "home;compute furniture;computer"
	filterVal := "(?i)compute\b"
	regexMatch, _ := regexp.MatchString(filterVal, brandName)
	fmt.Println(regexMatch)
}

This function returns me false when I use \b. Please help

答案1

得分: 6

双引号经常会吞噬 \。在处理正则表达式、SQL等情况下,始终使用原始字符串

filterVal := `(?i)compute\b`

Playground: http://play.golang.org/p/ePzZf5uLtw.

英文:

Double quotes often swallow the \. Always use raw strings with regexps, SQL, and such.

filterVal := `(?i)compute\b`

Playground: http://play.golang.org/p/ePzZf5uLtw.

huangapple
  • 本文由 发表于 2015年10月14日 22:16:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/33127836.html
匿名

发表评论

匿名网友

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

确定