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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器