Adding search and replace regexp utils

This commit is contained in:
DanB
2014-03-14 21:14:05 +01:00
parent 00b47c1367
commit 57be22dd87
3 changed files with 25 additions and 1 deletions

View File

@@ -85,7 +85,7 @@ type CGRConfig struct {
BalancerEnabled bool
SchedulerEnabled bool
CDRSEnabled bool // Enable CDR Server service
CDRSExtraFields []string //Extra fields to store in CDRs
CDRSExtraFields []string // Extra fields to store in CDRs
CDRSMediator string // Address where to reach the Mediator. Empty for disabling mediation. <""|internal>
CdreCdrFormat string // Format of the exported CDRs. <csv>
CdreExtraFields []string // Extra fields list to add in exported CDRs

View File

@@ -64,6 +64,7 @@ const (
COMMENT_CHAR = '#'
CSV_SEP = ','
FALLBACK_SEP = ';'
REGEXP_SEP = '~'
JSON = "json"
MSGPACK = "msgpack"
CSV_LOAD = "CSVLOAD"

View File

@@ -225,3 +225,26 @@ func ParseZeroRatingSubject(rateSubj string) (time.Duration, error) {
durStr := rateSubj[len(ZERO_RATING_SUBJECT_PREFIX):]
return time.ParseDuration(durStr)
}
// Used to parse extra fields definition into regexp rules
func ParseSearchReplaceRegexp(strRule string) (*regexp.Regexp, string, error) {
// String rule expected in the form ~hdr_name:s/match_rule/replace_rule/
getRuleRgxp := regexp.MustCompile(`:s\/(.+[^\\])\/(.+[^\\])\/`) // Make sure the separator / is not escaped in the rule
allMatches := getRuleRgxp.FindStringSubmatch(strRule)
if len(allMatches) != 3 { // Second and third groups are of interest to us
return nil, "", errors.New("Invalid Search&Replace rule.")
}
searchRegexp, err := regexp.Compile(allMatches[1])
if err != nil {
return nil, "", err
}
return searchRegexp, allMatches[2], nil
}
// Used to expand string sources, eg: extra fields
func RegexpSearchReplace(src string, searchRl *regexp.Regexp, replaceTpl string) string {
res := []byte{}
match := searchRl.FindStringSubmatchIndex(src)
res = searchRl.ExpandString(res, replaceTpl, src, match)
return string(res)
}