Skip to content

Commit 98ce9bc

Browse files
author
pratheesh
committed
support for custom reg matching pattern
1 parent e5c647f commit 98ce9bc

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

gocensorword.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ type CensorWordDetection struct {
2525
KeepSuffixChar bool
2626
SanitizeSpecialCharacters bool
2727
TextNormalization bool
28+
ReplaceCheckPattern string
2829
}
2930

3031
// this will create a new CensorWordDetection object
@@ -36,6 +37,7 @@ func NewDetector() *CensorWordDetection {
3637
KeepSuffixChar: false,
3738
SanitizeSpecialCharacters: true,
3839
TextNormalization: true,
40+
ReplaceCheckPattern: "(?i)%s",
3941
}
4042
}
4143

@@ -109,7 +111,7 @@ func (censor *CensorWordDetection) CensorWord(word string) (string, error) {
109111
for _, forbiddenWord := range censor.CensorList {
110112

111113
// should replace incase sensitive
112-
pattern := regexp.MustCompile(fmt.Sprintf(`(?i)%s`, forbiddenWord))
114+
pattern := regexp.MustCompile(fmt.Sprintf(censor.ReplaceCheckPattern, forbiddenWord))
113115
var replacePattern, prefix, suffix string
114116
wordLength := len(forbiddenWord)
115117

@@ -126,6 +128,7 @@ func (censor *CensorWordDetection) CensorWord(word string) (string, error) {
126128
"%s%s%s", prefix, strings.Repeat(censor.CensorReplaceChar, wordLength), suffix,
127129
)
128130
word = pattern.ReplaceAllString(word, replacePattern)
131+
129132
}
130133
// join the string
131134
return word, nil

gocensorword_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package gocensorword_test
22

33
import (
4+
"fmt"
45
"testing"
56

67
gocensorword "github.com/pcpratheesh/go-censorword"
@@ -77,3 +78,14 @@ func TestBadFullLength(t *testing.T) {
7778
resultString, _ := detector.CensorWord(word)
7879
require.Equal(t, resultString, "f**k post content a*****e s**k s****r")
7980
}
81+
82+
func TestBadWithCustomReplacePattern(t *testing.T) {
83+
var detector = gocensorword.NewDetector().SetCensorReplaceChar("*")
84+
detector.KeepPrefixChar = true
85+
detector.KeepSuffixChar = true
86+
detector.ReplaceCheckPattern = `\b%s\b`
87+
word := "pass ass fucker sucker"
88+
resultString, _ := detector.CensorWord(word)
89+
fmt.Println("resulr----", resultString)
90+
require.Equal(t, resultString, "pass a*s f****r s****r")
91+
}

0 commit comments

Comments
 (0)