正则表达式匹配
因为我是go语言,所以展示golang的
包:"github.com/dlclark/regexp2"
更多欢迎访问:www.zpf0000.com
// CanMatchRegexp return bool 某个字符串是否匹配正则表达式
func CanMatchRegexp(message string, regexpStr string) bool {re, err := regexp.Compile(regexpStr)if err != nil {logger.Error("CanMatchRegexp regexpStr error: ", err)return false}return re.MatchString(message)
}// CanMatchStringInRegexes return bool 某个字符串是否匹配切片中的任意一个正则表达式
func CanMatchStringInRegexes(message []byte, regexpStrings []string) bool {if len(regexpStrings) == 0 || message == nil {return true}for _, regexpStr := range regexpStrings {regexpStr1, err := strconv.Unquote(strings.Replace(strconv.Quote(regexpStr), `\\u`, `\u`, -1))if err != nil {logger.Error("CanMatchStringInRegexes regexpStrings error: ", err)} else {regexpStr = regexpStr1}logger.Info(fmt.Sprintf("message is %s, regexp is %s", string(message), regexpStr))if CanMatchRegexp(string(message), regexpStr) {return true}}return false
}// WildCardMatch 通配符匹配
func WildCardMatch(pattern string, value string) bool {result, _ := regexp.MatchString(wildCardToRegexp(pattern), value)return result
}// 通配符转换
func wildCardFullToRegexp(pattern string) string {tempArr := strings.Split(pattern, "*")for i, literal := range tempArr {tempArr[i] = regexp.QuoteMeta(literal)}return strings.Join(tempArr, ".*")
}// RemoveHyperlink 提取超链接中的url
func RemoveHyperlink(hyperlink string) string {re := regexp.MustCompile(`<a[^>]+href=["']([^"']+)["'][^>]*>.*?</a>`)match := re.FindStringSubmatch(hyperlink)if len(match) > 1 {return strings.Replace(hyperlink, match[0], "", -1)}return hyperlink
}// Regexp2FindAllString Regex2包,返回所以能匹配正则的字符串
func Regexp2FindAllString(re *regexp2.Regexp, s string) []string {var matches []stringm, _ := re.FindStringMatch(s)for m != nil {matches = append(matches, m.String())m, _ = re.FindNextMatch(m)}return matches
}