Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

正则表达式 #9

Open
kevinyan815 opened this issue Sep 8, 2019 · 0 comments
Open

正则表达式 #9

kevinyan815 opened this issue Sep 8, 2019 · 0 comments

Comments

@kevinyan815
Copy link
Owner

kevinyan815 commented Sep 8, 2019

验证字符串匹配模式

package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`^\d+$`)
	fmt.Println(re.MatchString("13877474"))
}

子模式匹配

package main

import (
	"fmt";
	"regexp"
)

func main() {
re := regexp.MustCompile("\\$\\{(.*?)\\}")
match := re.FindStringSubmatch("git commit -m '${abc}'")
	fmt.Println(match)
}

SKU有两类一类是定值的比如"sku_goods1_9000_0",这种就需要验证下单参数的中的金额与SKU中的金额是否是一样, 另外一种充值订单对应的SKU不是定值的就不用验证,比如"sku_recharge_other_0",写一个函数完成这个功能。

// 检查创建订单时参数里的amount与skuSymbol中的amount是否一致
func checkSkuAmount(skuSymbol string, amount int64) bool {
	if strings.Contains(skuSymbol, "other") {
		return true
	}
	re := regexp.MustCompile(`[A-Za-z_]+?(\d+?)_\d+$`)
	match := re.FindStringSubmatch(skuSymbol)
	if match == nil {
		return false
	}
	skuAmount, err := strconv.ParseInt(match[1], 10, 64)
	if err != nil || skuAmount != amount {
		return false
	}

	return true
}

正则替换

隐藏姓名中间部分,只展示首尾

func HideUserName(userName string) string {
	if userName == "" {
		return ""
	}
	re := regexp.MustCompile(`^(.).+?(.)?$`)
	result := re.ReplaceAllString(userName, `$1*$2`)
	return result
}

golang 正则库CheatSheet

@kevinyan815 kevinyan815 changed the title 常用正则表达式 正则表达式 Sep 8, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant