首页 > 解决方案 > 如何检查字符串是否包含点(句点)?

问题描述

我想找出一个字符串是否包含一个或多个点。这是我的代码:

package main 
  
import ( 
    "fmt"
    "regexp"
) 
    
func main() { 
    s1 := "Welcome to dotless string"
    p1 := "."
  
    res1, e := regexp.MatchString(p1, s1) 
    fmt.Println("Result and Error is:", res1, e) 
  
} 

但它不起作用:

Result and Error is: true <nil>

虽然它应该返回false <nil>

我该如何解决这个问题?

标签: regexgo

解决方案


.是正则表达式中匹配任何单个字符的特殊字符。为了从字面上匹配它,它需要被转义:"\\."

反斜杠加倍是因为我们需要在字符串文字中转义它的特殊含义。


推荐阅读