首页 > 其他 > 详细

Go 验证是否字符串包含中文

时间:2020-01-20 18:19:43      阅读:64      评论:0      收藏:0      [点我收藏+]

发现一个验证字符串是否包含中文滴时候,发现一个比正则更好使滴方法,而且是golang 自带滴验证。

不需要自己写正则验证,代码如下:

package main

import (
    "fmt"
    "regexp"
    "unicode"
)

func main() {
    s1 := "我是中国人hello word!,2020 street 188#"
    var count int
    for _, v := range s1 {
        if unicode.Is(unicode.Han, v) {
            fmt.Println("找到中文")
            count++
        }
    }
    fmt.Println(count)
    fmt.Println(IsChineseChar(s1))
}

// 或者封装函数调用
func IsChineseChar(str string) bool {

    for _, r := range str {
        if unicode.Is(unicode.Scripts["Han"], r) || (regexp.MustCompile("[\u3002\uff1b\uff0c\uff1a\u201c\u201d\uff08\uff09\u3001\uff1f\u300a\u300b]").MatchString(string(r))) {
            return true
        }
    }
    return false
}

比正则好用

Go 验证是否字符串包含中文

原文:https://www.cnblogs.com/phpper/p/12218771.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!