Go string 字符串

发布时间: 更新时间: 总字数:836 阅读时间:2m 作者: IP属地: 分享 复制网址

本文介绍在Golang中与字符串和字节切片相关的使用,并提供相应的示例供初学者参考。

介绍

  • bytes:将buffer对象转化为字节切片
  • string:将buffer对象转化为字符串

相关的golang包:

  • strings:字符串相关操作工具类
  • bytes:字节相关操作工具类
  • strconv:字符串与其他类型相关转化工具类
  • utf8/unicode:unicode 相关操作工具类
  • 定义参考
type stringStruct struct {
	str unsafe.Pointer
	len int
}

示例

bytes 和 string 转化示例

字符切片和字符串相互转化

package main

import (
	"bytes"
	"fmt"
)

func ExampleByteSlice() {
	// 字节切片
	var bs = []byte{'a', 'b', 'c'}
	fmt.Printf("%T %#v\n", bs, bs)

	// 字节切片转字符串
	s := string(bs)
	fmt.Printf("%T %#v\n", s, s)

	// 字符串转字节切片
	bs = []byte(s)
	fmt.Printf("%T %#v\n", bs, bs)

	// bytes 包
	fmt.Println(bytes.Compare([]byte("abc"), []byte("xyz")))
	fmt.Println(bytes.Index([]byte("abc"), []byte("a")))
	fmt.Println(bytes.Contains([]byte("abc"), []byte("a")))

	// Output:
	//[]uint8 []byte{0x61, 0x62, 0x63}
	//string "abc"
	//[]uint8 []byte{0x61, 0x62, 0x63}
	//-1
	//0
	//true
}

unicode 计数示例

使用 unicode/utf8 包计算 unicode (rune)字符串长度

package main

import (
	"fmt"
	"unicode/utf8"
)

func ExampleUnicodeCount() {
	//unicode 字符计算长度
	s1 := "Iam中国人"
	fmt.Println(len(s1))
	fmt.Println(utf8.RuneCountInString(s1))

	// Output:
	//12
	//6
}

正则

常用正则表达式汇总

功能:有查找、匹配、替换、分隔字符串

常用语法:

  • ^ 开头
  • $ 结尾
  • . 任意字符
  • \d 数字,区分
  • \D 非数字,同 [^0-9]
  • \S 非空白字符
  • \s 空白字符
  • \d 数字
  • \w 大小写英文字母、数字、下划线,通 [a-zA-Z0-9_]
  • (abc)|(xyz) 分组
  • [0-9] 0~9共10个数字
  • [a-z] 小写英文字母 [a\-z] a - z 三个字符
  • [^a-z] 非小写英文字母
  • ? 0个或1个
  • + 至少一个
  • * 任意多个
  • {n} n 个数量
  • {n,} 至少 n 个
  • {n,m} 字符串数量在 n<= x <=m

实现方式:

  • func Match(pattern string, b []byte) (matched bool, err error)
  • func MatchReader(pattern string, r io.RuneReader) (matched bool, err error)
  • func MatchString(pattern string, s string) (matched bool, err error)
  • Regexp struct
    • func Compile(expr string) (*Regexp, error)
    • func MustCompile(str string) *Regexp
    • Findxxx
    • Matchxxx
    • Replacexxx
    • Split
  • 贪婪模式(?U)

示例

package main

import (
	"fmt"
	"regexp"
	"strings"
)

func main() {
	// 正则开头匹配
	pattern := "^135"
	fmt.Println(regexp.MatchString(pattern, "1352359110x")) // true <nil>
	fmt.Println(regexp.MatchString(pattern, "139499xxx"))   // false <nil>
	fmt.Println(strings.HasPrefix("1352359110x", "135"))    // true

	// 手机号检测
	//pattern = "^135[0-9]{8}$"
	pattern = "^135\\d{8}$"
	fmt.Println(regexp.MatchString(pattern, "13523591100")) // true <nil>

	//pattern = "^13[5|9]\\d{8}$"
	//pattern = "^13[59]\\d{8}$"
	//pattern = "^(135|139)\\d{8}$"
	//pattern = "^(135)|(139)\\d{8}$"
	pattern = "^(135)|(139)[0-9]{8}$"
	fmt.Println(regexp.MatchString(pattern, "13523591100")) // true <nil>
	fmt.Println(regexp.MatchString(pattern, "13949912345")) // true <nil>

	// 邮箱检测
	//pattern = "[0-9a-zA-Z]{2,64}@[a-z0-9]{1,64}\\.(cn|com|net)$"
	pattern = "[0-9a-zA-Z]{2,64}@[a-z0-9]{1,64}[.](cn|com|net)$"
	fmt.Println(regexp.MatchString(pattern, "me@xiexianbin.cn")) // true <nil>

	// 原始字符串
	fmt.Println(regexp.QuoteMeta(`Escaping symbols like: .+*?()|[]{}^$`)) // Escaping symbols like: \.\+\*\?\(\)\|\[\]\{\}\^\$
	fmt.Println(regexp.MatchString(regexp.QuoteMeta("^a"), "^abcd"))
}
package main

import (
	"fmt"
	"regexp"
)

func main() {
	expr := "135[0-9]{8}"
	reg, err := regexp.Compile(expr)
	if err != nil {
		fmt.Println(err.Error())
	}

	fmt.Println(reg.FindString("sdfsd13523591100sfdsdf"))
	flag := reg.MatchString("13523591100")
	fmt.Println(flag)
	fmt.Println(reg.FindAllString("sdfsd13523591100sfdsdfsdfsd13523591100sfdsdf", -1)) // [13523591100 13523591100]

	// 替换字符串
	fmt.Println(reg.ReplaceAllString("sdfsd13523591100sfdsdf", "135xxxx")) // sdfsd135xxxxsfdsdf

	// 分隔
	reg, err = regexp.Compile("[:;\t,]")
	fmt.Println(reg.Split("sdfsd:13523591100;sfdsdfsdfsd\t13523591100,sfdsdf", -1)) // [sdfsd 13523591100 sfdsdfsdfsd 13523591100 sfdsdf]

	// 加号表示一个
	//reg, err = regexp.Compile("[a-z]+") // [a b c d e]
	reg, err = regexp.Compile("[ab0-9]+") // [a1b2 3 4 5]
	//reg, err = regexp.Compile("(?U)[ab0-9]+") // 贪婪模式 [a 1 b 2 3 4 5]
	fmt.Println(reg.FindAllString("a1b2c3d4e5", -1))

	// 将非贪婪模式转化为贪婪模式
	reg.Longest()
	fmt.Println(reg.FindAllString("a1b2c3d4e5", -1))
}
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数