dongmu9253 2013-09-30 21:37
浏览 108
已采纳

去正则表达式来检测反斜杠字符

In go, how do I detect \ back slash character itself?

 str := "I have Hello \"World\""
 var validID = regexp.MustCompile(`[.!?]`)

this is how I detect . ! ? characters but

 var validID = regexp.MustCompile(`[\]`)

does not detect the backslash in the string.

How do I denote backslash in go regular expression?

  • 写回答

1条回答 默认 最新

  • doujing5150 2013-09-30 21:40
    关注

    You'll need to escape it, even in a character class; otherwise it will think you're trying to escape the ]:

    var validID = regexp.MustCompile(`[\\]`)
    

    But for that matter, you can just get rid of the character class entirely:

    var validID = regexp.MustCompile(`\\`)
    

    Also note that the string "I have Hello \"World\"" does not actually contain any backlashes. \" is an escape sequence a double quote. If you want to create a string with backslashes use:

    str := "I have Hello \\\"World\\\""
    

    Or

    str := `I have Hello \"World\"`
    

    A working demonstration can be found here.

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

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程