Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions regex/rstring/string.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,12 @@ func ContainsSpecialChars(s string) bool {

return !isStringAlphabetic(s)
}

// RemoveLineBreaks removes all line breaks from a string using a regex.
// As per https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#lineending,
// Any Unicode linebreak sequence, is equivalent to \u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029] .
func RemoveLineBreaks(s string) string {
re := regexp.MustCompile(`\x{000D}\x{000A}|[\x{000A}\x{000B}\x{000C}\x{000D}\x{0085}\x{2028}\x{2029}]`)

return re.ReplaceAllString(s, ``)
}
26 changes: 26 additions & 0 deletions regex/rstring/string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,29 @@ func TestContainsSpecialChars(t *testing.T) {
})
}
}

func TestRemoveLineBreaks(t *testing.T) {
type test struct {
name string
input string
output string
}

tests := []test{
{name: "MultipleLineBreaks", input: "One\r,\r\ntwo\u0085 three\u2028!\u2029'", output: "One,two three!'"},
{name: "WindowsLineBreak", input: "Win\r\n", output: "Win"},
{name: "MacLineBreak", input: "Mac\r", output: "Mac"},
}

for _, tc := range tests {
tc := tc
t.Run(tc.name, func(t *testing.T) {
result := rstring.RemoveLineBreaks(tc.input)
diff := reflect.DeepEqual(result, tc.output)
if !diff {
t.Errorf("RemoveLineBreaks(%s) Failed: expected %s, actual %s",
tc.input, tc.output, result)
}
})
}
}