duanma8207
2016-02-04 04:50
浏览 102
已采纳

带有拉丁字符的Golang正则表达式边界

I have a small tricky issue about golang regex. seems \b boundering option doesn't work when I put latein chars like this.

I expected that é should be treated as a regular char.. but it's treated as one of boundering wards.

package main

import (
    "fmt"
    "regexp"
)

func main() {   
    r, _ := regexp.Compile(`\b(vis)\b`)
    fmt.Println(r.MatchString("re vis e"))
    fmt.Println(r.MatchString("revise"))
    fmt.Println(r.MatchString("révisé"))
}

result was:

true 
false 
true

Please give me any suggestion how to deal with r.MatchString("révisé") as false ?

Thank you

图片转代码服务由CSDN问答提供 功能建议

我对golang正则表达式有一个小棘手的问题。 似乎 \ b 绑定选项没有 “T工作 当我把latein字符这样的。

我预期的电子的应该被视为一个普通字符.. 但它当作一个 病房。

 包main 
 
import(
“ fmt” 
“ regexp” 
)
 
func main(){
r,_:= regexp。 编译(`\ b(vis)\ b`)
 fmt.Println(r.MatchString(“ re vis e”))
 fmt.Println(r.MatchString(“ revise”))
 fmt.Println(  r.MatchString(“révisé”))
} 
   
 
 

结果为:

  true 
false \  ntrue 
   
 
 

请给我任何建议,如何处理 r.MatchString(“révisé”) false

谢谢

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duandou8120 2016-02-04 05:09
    已采纳

    The issue is that \b is only for boundaries around ASCII characters, as stated in the docs:

    at ASCII word boundary (\w on one side and \W, \A, or \z on the other)

    And é is not ASCII. But, you can make your own \b replacement by combining other regex shortcuts. Here is a simple solution that solves the case given in the question, though you may want to add more thorough matching:

    package main
    
    import (
        "fmt"
        "regexp"
    )
    
    func main() {   
        r, _ := regexp.Compile(`(?:\A|\s)(vis)(?:\s|\z)`)
        fmt.Println(r.MatchString("vis")) // added this case
        fmt.Println(r.MatchString("re vis e"))
        fmt.Println(r.MatchString("revise"))
        fmt.Println(r.MatchString("révisé"))
    }
    

    Running this gives:

    true
    true
    false
    false
    

    What this solution does is essentially replace \b with (?:\A|\z|\s), which means "a non-capturing group with one of the following: start of string, end of string or whitespace". You may want to add other possibilities here, like punctuation.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题