github.com/aldelo/common@v1.5.1/helper-regex.go (about) 1 package helper 2 3 /* 4 * Copyright 2020-2023 Aldelo, LP 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 import ( 20 "regexp" 21 "strings" 22 ) 23 24 // RegexReplaceSubString will search for substring between subStringFrom and subStringTo, replace with the replaceWith string, and optionally case insensitive or not 25 func RegexReplaceSubString(source string, subStringFrom string, subStringTo string, replaceWith string, caseInsensitive bool) string { 26 // setup regex 27 ci := "" 28 29 if caseInsensitive { 30 ci = "(?i)" 31 } 32 33 regE := regexp.MustCompile(ci + subStringFrom + "(.*)" + subStringTo) 34 35 // find sub match 36 m := regE.FindStringSubmatch(source) 37 38 if len(m) >= 1 { 39 // found one or more match, use the first found only 40 return strings.ReplaceAll(source, m[0], replaceWith) 41 } else { 42 // no match found, return source as is 43 return source 44 } 45 }