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

带有拉丁字符的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

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?