GolangNote

Golang笔记

Golang 计算字符串中包含某个或某些字符集的个数

Permalink

有时候需要得出字符串中包含某个字符的个数,或者是包含某些字符集的个数,这里使用 stringsregexp 库实现。

如果是只计算某个字符串包含单个字符的个数,只用 strings.Count 函数就可以

Go: strings.Count
1
strings.Count("abcdassa", "a")

结果是 3

有时候要计算字符集,如 as 就得用正则来实现

Go: 正则
1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import (
    "fmt"
    "regexp"
)

func main() {
    orExp := regexp.MustCompile("a|s")

    matches := orExp.FindAllStringIndex("abcdassa", -1)
    fmt.Println(len(matches))
}

结果会输出 5

本文网址: https://golangnote.com/topic/270.html 转摘请注明来源

Related articles

Golang 把cookie 字符串解析为cookie 结构

在做爬虫时有时候会遇到需要带已登录的 cookie 请求,这个时候最简单的方法是在浏览器登录后,在开发者面板找到cookie 字符串,然后拷贝粘贴。这就面临一个问题需要把cookie 字符串解析成Go 语言 cookie 结构体。...

Write a Comment to "Golang 计算字符串中包含某个或某些字符集的个数"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 0ms