🎯 Exemplos recomendados
Balanced sample collections from various categories for you to explore
Exemplos de Processamento de Strings Web Go
Exemplos de processamento de strings Web Go incluindo divisão/junção de strings, expressões regulares e substituição de strings
💻 Divisão/Junção de Strings go
🟢 simple
⭐⭐
Dividir strings por separadores e juntar fatias de strings usando o pacote strings do Go
⏱️ 20 min
🏷️ go, web, string processing
Prerequisites:
Basic Go, strings package
// Web Go String Split/Join Examples
// Using Go strings package for string splitting and joining
package main
import (
"fmt"
"strings"
)
// 1. Basic String Splitting
// SplitBySpace splits a string by whitespace
func SplitBySpace(text string) []string {
return strings.Fields(text)
}
// SplitByDelimiter splits a string by a delimiter
func SplitByDelimiter(text, delimiter string) []string {
return strings.Split(text, delimiter)
}
// SplitByDelimiterN splits a string by delimiter with max splits
func SplitByDelimiterN(text, delimiter string, n int) []string {
return strings.SplitN(text, delimiter, n)
}
// SplitAfterDelimiter splits after each occurrence of delimiter
func SplitAfterDelimiter(text, delimiter string) []string {
return strings.SplitAfter(text, delimiter)
}
// SplitAfterDelimiterN splits after delimiter with max splits
func SplitAfterDelimiterN(text, delimiter string, n int) []string {
return strings.SplitAfterN(text, delimiter, n)
}
// 2. Advanced Splitting
// SplitByAny splits by any of the specified characters
func SplitByAny(text, chars string) []string {
return strings.FieldsFunc(text, func(r rune) bool {
return strings.ContainsRune(chars, r)
})
}
// SplitByWhitespace splits by any whitespace
func SplitByWhitespace(text string) []string {
return strings.Fields(text)
}
// SplitLines splits text into lines
func SplitLines(text string) []string {
return strings.Split(text, "
")
}
// SplitByComma splits by comma
func SplitByComma(text string) []string {
return strings.Split(text, ",")
}
// 3. String Joining
// JoinStrings joins a slice of strings with a separator
func JoinStrings(parts []string, separator string) string {
return strings.Join(parts, separator)
}
// JoinWithSpace joins strings with space
func JoinWithSpace(parts []string) string {
return strings.Join(parts, " ")
}
// JoinWithComma joins strings with comma
func JoinWithComma(parts []string) string {
return strings.Join(parts, ", ")
}
// JoinWithNewline joins strings with newline
func JoinWithNewline(parts []string) string {
return strings.Join(parts, "
")
}
// JoinWithPipe joins strings with pipe
func JoinWithPipe(parts []string) string {
return strings.Join(parts, " | ")
}
// 4. Split and Join Operations
// SplitAndJoin splits by one delimiter and joins with another
func SplitAndJoin(text, splitBy, joinWith string) string {
parts := strings.Split(text, splitBy)
return strings.Join(parts, joinWith)
}
// RemoveDelimiter removes delimiter from text
func RemoveDelimiter(text, delimiter string) string {
return strings.Join(strings.Split(text, delimiter), "")
}
// ReplaceDelimiters replaces multiple delimiters with one
func ReplaceDelimiters(text string, delimiters []string, newDelimiter string) string {
result := text
for _, delim := range delimiters {
result = strings.Join(strings.Split(result, delim), newDelimiter)
}
return result
}
// 5. Parsing and Formatting
// ParseKeyValue parses key-value pairs
func ParseKeyValue(text, pairDelimiter, kvDelimiter string) map[string]string {
result := make(map[string]string)
pairs := strings.Split(text, pairDelimiter)
for _, pair := range pairs {
kv := strings.SplitN(pair, kvDelimiter, 2)
if len(kv) == 2 {
key := strings.TrimSpace(kv[0])
value := strings.TrimSpace(kv[1])
if key != "" {
result[key] = value
}
}
}
return result
}
// ParseCSV parses a simple CSV line
func ParseCSV(line string) []string {
return strings.Split(line, ",")
}
// ParseWords extracts words from text
func ParseWords(text string) []string {
return strings.Fields(text)
}
// ParseSentences splits text into sentences
func ParseSentences(text string) []string {
// Simple sentence splitting by period, exclamation, question mark
sentences := strings.FieldsFunc(text, func(r rune) bool {
return r == '.' || r == '!' || r == '?'
})
// Trim whitespace from each sentence
for i, sentence := range sentences {
sentences[i] = strings.TrimSpace(sentence)
}
return sentences
}
// 6. String Building
// BuildPath builds a path from parts
func BuildPath(parts ...string) string {
return strings.Join(parts, string('/'))
}
// BuildSentence builds a sentence from words
func BuildSentence(words []string) string {
return strings.Join(words, " ")
}
// BuildCSV builds a CSV line from parts
func BuildCSV(parts []string) string {
return strings.Join(parts, ",")
}
// BuildKeyValues builds key-value string
func BuildKeyValues(kv map[string]string, pairDelim, kvDelim string) string {
var pairs []string
for key, value := range kv {
pairs = append(pairs, key+kvDelim+value)
}
return strings.Join(pairs, pairDelim)
}
// 7. String Trimming
// TrimSpace trims whitespace from both ends
func TrimSpace(text string) string {
return strings.TrimSpace(text)
}
// TrimPrefix trims prefix from string
func TrimPrefix(text, prefix string) string {
return strings.TrimPrefix(text, prefix)
}
// TrimSuffix trims suffix from string
func TrimSuffix(text, suffix string) string {
return strings.TrimSuffix(text, suffix)
}
// TrimChars trims specified characters from both ends
func TrimChars(text, cutset string) string {
return strings.Trim(text, cutset)
}
// TrimLeft trims characters from left
func TrimLeft(text, cutset string) string {
return strings.TrimLeft(text, cutset)
}
// TrimRight trims characters from right
func TrimRight(text, cutset string) string {
return strings.TrimRight(text, cutset)
}
// 8. Split and Filter
// SplitAndEmpty splits and removes empty strings
func SplitAndEmpty(text, delimiter string) []string {
parts := strings.Split(text, delimiter)
var result []string
for _, part := range parts {
if part != "" {
result = append(result, part)
}
}
return result
}
// SplitAndTrim splits and trims each part
func SplitAndTrim(text, delimiter string) []string {
parts := strings.Split(text, delimiter)
var result []string
for _, part := range parts {
trimmed := strings.TrimSpace(part)
if trimmed != "" {
result = append(result, trimmed)
}
}
return result
}
// SplitAndUnique splits and removes duplicates
func SplitAndUnique(text, delimiter string) []string {
parts := strings.Split(text, delimiter)
seen := make(map[string]bool)
var result []string
for _, part := range parts {
trimmed := strings.TrimSpace(part)
if trimmed != "" && !seen[trimmed] {
seen[trimmed] = true
result = append(result, trimmed)
}
}
return result
}
// 9. Utility Functions
// CountOccurrences counts occurrences of substring
func CountOccurrences(text, substring string) int {
return strings.Count(text, substring)
}
// Contains checks if text contains substring
func Contains(text, substring string) bool {
return strings.Contains(text, substring)
}
// ContainsAny checks if text contains any of the characters
func ContainsAny(text, chars string) bool {
return strings.ContainsAny(text, chars)
}
// HasPrefix checks if text has prefix
func HasPrefix(text, prefix string) bool {
return strings.HasPrefix(text, prefix)
}
// HasSuffix checks if text has suffix
func HasSuffix(text, suffix string) bool {
return strings.HasSuffix(text, suffix)
}
// Usage Examples
func main() {
fmt.Println("=== Web Go String Split/Join Examples ===
")
// 1. Basic splitting
fmt.Println("--- 1. Basic Splitting ---")
text := "hello world go programming"
fmt.Printf("Split by space: %v
", SplitBySpace(text))
fmt.Printf("Split by comma: %v
", SplitByDelimiter("a,b,c,d", ","))
// 2. Advanced splitting
fmt.Println("
--- 2. Advanced Splitting ---")
fmt.Printf("Split by any of ,;|: %v
", SplitByAny("a,b;c|d", ",;|"))
fmt.Printf("Split lines: %v
", SplitLines("line1
line2
line3"))
// 3. Joining
fmt.Println("
--- 3. Joining ---")
words := []string{"Go", "is", "awesome"}
fmt.Printf("Join with space: %s
", JoinWithSpace(words))
fmt.Printf("Join with comma: %s
", JoinWithComma(words))
// 4. Split and join
fmt.Println("
--- 4. Split and Join ---")
fmt.Printf("Replace delimiter: %s
", SplitAndJoin("a-b-c-d", "-", "."))
// 5. Parsing
fmt.Println("
--- 5. Parsing ---")
kvText := "name=John;age=30;city=NYC"
fmt.Printf("Parse key-value: %v
", ParseKeyValue(kvText, ";", "="))
// 6. Building
fmt.Println("
--- 6. Building ---")
fmt.Printf("Build path: %s
", BuildPath("home", "user", "docs"))
kvMap := map[string]string{"name": "John", "age": "30"}
fmt.Printf("Build key-value: %s
", BuildKeyValues(kvMap, ";", "="))
// 7. Trimming
fmt.Println("
--- 7. Trimming ---")
fmt.Printf("Trim space: '%s'
", TrimSpace(" hello "))
fmt.Printf("Trim prefix: '%s'
", TrimPrefix("prefix_text", "prefix_"))
// 8. Split and filter
fmt.Println("
--- 8. Split and Filter ---")
fmt.Printf("Split and empty: %v
", SplitAndEmpty("a,,b,c,,d", ","))
fmt.Printf("Split and trim: %v
", SplitAndTrim(" a , b , c ", ","))
// 9. Utilities
fmt.Println("
--- 9. Utilities ---")
fmt.Printf("Count occurrences: %d
", CountOccurrences("hello hello world", "hello"))
fmt.Printf("Contains: %t
", Contains("hello world", "world"))
fmt.Printf("Has prefix: %t
", HasPrefix("hello world", "hello"))
fmt.Println("
=== All String Split/Join Examples Completed ===")
}
💻 Correspondência de Padrões Regex go
🟡 intermediate
⭐⭐⭐
Usar expressões regulares para correspondência de padrões, validação e pesquisa de texto com o pacote regexp do Go
⏱️ 30 min
🏷️ go, web, string processing, regex
Prerequisites:
Intermediate Go, regexp package, regex syntax
// Web Go Regex Pattern Matching Examples
// Using Go regexp package for regular expression operations
package main
import (
"fmt"
"regexp"
"strings"
)
// 1. Basic Pattern Matching
// MatchPattern checks if text matches a pattern
func MatchPattern(text, pattern string) bool {
matched, err := regexp.MatchString(pattern, text)
if err != nil {
return false
}
return matched
}
// FindPattern finds first match of pattern
func FindPattern(text, pattern string) string {
re := regexp.MustCompile(pattern)
return re.FindString(text)
}
// FindAllPatterns finds all matches of pattern
func FindAllPatterns(text, pattern string) []string {
re := regexp.MustCompile(pattern)
return re.FindAllString(text, -1)
}
// FindPatternSubmatch finds pattern with submatches
func FindPatternSubmatch(text, pattern string) []string {
re := regexp.MustCompile(pattern)
return re.FindStringSubmatch(text)
}
// 2. Common Validation Patterns
// IsValidEmail validates email format
func IsValidEmail(email string) bool {
pattern := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
return MatchPattern(email, pattern)
}
// IsValidURL validates URL format
func IsValidURL(url string) bool {
pattern := `^https?://[a-zA-Z0-9.-]+(\.[a-zA-Z]{2,})?(/.*)?$`
return MatchPattern(url, pattern)
}
// IsValidPhoneNumber validates phone number format
func IsValidPhoneNumber(phone string) bool {
pattern := `^\+?1?-?\(?[0-9]{3}\)?[ -]?[0-9]{3}[ -]?[0-9]{4}$`
return MatchPattern(phone, pattern)
}
// IsValidIPAddress validates IP address format
func IsValidIPAddress(ip string) bool {
pattern := `^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$`
return MatchPattern(ip, pattern)
}
// IsValidHexColor validates hex color code
func IsValidHexColor(color string) bool {
pattern := `^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$`
return MatchPattern(color, pattern)
}
// IsValidUsername validates username format
func IsValidUsername(username string) bool {
pattern := `^[a-zA-Z0-9_]{3,16}$`
return MatchPattern(username, pattern)
}
// IsValidPassword validates password strength
func IsValidPassword(password string) bool {
// At least 8 characters, 1 uppercase, 1 lowercase, 1 number
pattern := `^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{8,}$`
return MatchPattern(password, pattern)
}
// IsValidPostalCode validates postal code format
func IsValidPostalCode(code string) bool {
pattern := `^\d{5}(-\d{4})?$`
return MatchPattern(code, pattern)
}
// IsValidCreditCard validates credit card number
func IsValidCreditCard(card string) bool {
// Remove spaces and dashes
card = strings.ReplaceAll(card, " ", "")
card = strings.ReplaceAll(card, "-", "")
pattern := `^\d{13,19}$`
return MatchPattern(card, pattern)
}
// 3. Text Extraction
// ExtractEmails extracts all email addresses from text
func ExtractEmails(text string) []string {
pattern := `[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}`
return FindAllPatterns(text, pattern)
}
// ExtractURLs extracts all URLs from text
func ExtractURLs(text string) []string {
pattern := `https?://[a-zA-Z0-9.-]+(\.[a-zA-Z]{2,})?(/[^\s]*)?`
return FindAllPatterns(text, pattern)
}
// ExtractPhoneNumbers extracts all phone numbers from text
func ExtractPhoneNumbers(text string) []string {
pattern := `\+?1?-?\(?[0-9]{3}\)?[ -]?[0-9]{3}[ -]?[0-9]{4}`
return FindAllPatterns(text, pattern)
}
// ExtractIPAddresses extracts all IP addresses from text
func ExtractIPAddresses(text string) []string {
pattern := `((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)`
return FindAllPatterns(text, pattern)
}
// ExtractHashtags extracts all hashtags from text
func ExtractHashtags(text string) []string {
pattern := `#\w+`
return FindAllPatterns(text, pattern)
}
// ExtractMentions extracts all @mentions from text
func ExtractMentions(text string) []string {
pattern := `@\w+`
return FindAllPatterns(text, pattern)
}
// ExtractNumbers extracts all numbers from text
func ExtractNumbers(text string) []string {
pattern := `-?\d+\.?\d*`
return FindAllPatterns(text, pattern)
}
// ExtractDates extracts dates in various formats
func ExtractDates(text string) []string {
pattern := `\d{1,2}[/-]\d{1,2}[/-]\d{2,4}`
return FindAllPatterns(text, pattern)
}
// 4. Text Search and Replace
// ReplacePattern replaces pattern matches with replacement
func ReplacePattern(text, pattern, replacement string) string {
re := regexp.MustCompile(pattern)
return re.ReplaceAllString(text, replacement)
}
// ReplacePatternFunc replaces matches using a function
func ReplacePatternFunc(text, pattern string, repl func(string) string) string {
re := regexp.MustCompile(pattern)
return re.ReplaceAllStringFunc(text, repl)
}
// FindPatternIndices finds indices of pattern matches
func FindPatternIndices(text, pattern string) [][]int {
re := regexp.MustCompile(pattern)
return re.FindAllStringIndex(text, -1)
}
// FindPatternStringIndex finds first match with its indices
func FindPatternStringIndex(text, pattern string) (string, []int) {
re := regexp.MustCompile(pattern)
loc := re.FindStringIndex(text)
if loc == nil {
return "", nil
}
return text[loc[0]:loc[1]], loc
}
// 5. Group Extraction
// ExtractGroups extracts named groups from pattern
func ExtractGroups(text, pattern string) map[string]string {
re := regexp.MustCompile(pattern)
matches := re.FindStringSubmatch(text)
if matches == nil {
return nil
}
result := make(map[string]string)
names := re.SubexpNames()
for i, name := range names {
if i > 0 && i < len(matches) && name != "" {
result[name] = matches[i]
}
}
return result
}
// ExtractAllGroups extracts all group matches
func ExtractAllGroups(text, pattern string) []map[string]string {
re := regexp.MustCompile(pattern)
matches := re.FindAllStringSubmatch(text, -1)
if matches == nil {
return nil
}
var results []map[string]string
names := re.SubexpNames()
for _, match := range matches {
result := make(map[string]string)
for i, name := range names {
if i > 0 && i < len(match) && name != "" {
result[name] = match[i]
}
}
results = append(results, result)
}
return results
}
// 6. Advanced Patterns
// MatchHTMLTag matches HTML tags
func MatchHTMLTag(text, tagName string) bool {
pattern := fmt.Sprintf("<%s\b[^>]*>(.*?)</%s>", tagName, tagName)
return MatchPattern(text, pattern)
}
// ExtractHTMLContent extracts content from HTML tags
func ExtractHTMLContent(text, tagName string) []string {
pattern := fmt.Sprintf("<%s\b[^>]*>(.*?)</%s>", tagName, tagName)
re := regexp.MustCompile(pattern)
matches := re.FindAllStringSubmatch(text, -1)
var contents []string
for _, match := range matches {
if len(match) > 1 {
contents = append(contents, match[1])
}
}
return contents
}
// ExtractCSVFields extracts fields from CSV line
func ExtractCSVFields(line string) []string {
pattern := `(?:^|,)(\"([^\"]*\"|""|[^,]*)"|([^,]*))`
re := regexp.MustCompile(pattern)
matches := re.FindAllStringSubmatch(line, -1)
var fields []string
for _, match := range matches {
if len(match) > 2 {
field := match[2]
if field == "" {
field = match[3]
}
// Unescape quotes
field = strings.ReplaceAll(field, `""`, `"`)
fields = append(fields, field)
}
}
return fields
}
// 7. String Analysis
// CountPatternOccurrences counts pattern occurrences
func CountPatternOccurrences(text, pattern string) int {
re := regexp.MustCompile(pattern)
return len(re.FindAllString(text, -1))
}
// FindWordsStartingWith finds words starting with prefix
func FindWordsStartingWith(text, prefix string) []string {
pattern := fmt.Sprintf("\b%s\w*", prefix)
return FindAllPatterns(text, pattern)
}
// FindWordsEndingWith finds words ending with suffix
func FindWordsEndingWith(text, suffix string) []string {
pattern := fmt.Sprintf("\b\w*%s\b", suffix)
return FindAllPatterns(text, pattern)
}
// FindWholeWord finds whole word occurrences
func FindWholeWord(text, word string) []string {
pattern := fmt.Sprintf("\b%s\b", word)
return FindAllPatterns(text, pattern)
}
// 8. Case Sensitivity
// FindCaseInsensitive finds pattern ignoring case
func FindCaseInsensitive(text, pattern string) []string {
re := regexp.MustCompile((?i) + pattern)
return re.FindAllString(text, -1)
}
// ReplaceCaseInsensitive replaces pattern ignoring case
func ReplaceCaseInsensitive(text, pattern, replacement string) string {
re := regexp.MustCompile((?i) + pattern)
return re.ReplaceAllString(text, replacement)
}
// 9. Multiline Matching
// FindMultiline matches across multiple lines
func FindMultiline(text, pattern string) []string {
re := regexp.MustCompile((?s) + pattern)
return re.FindAllString(text, -1)
}
// ExtractCodeBlocks extracts code blocks from text
func ExtractCodeBlocks(text, language string) []string {
// Find code blocks for specified language
marker := language
var blocks []string
// Simple implementation: split by language name and extract content
parts := strings.Split(text, marker)
for i := 1; i < len(parts); i += 2 {
if i < len(parts) {
blocks = append(blocks, strings.TrimSpace(parts[i]))
}
}
return blocks
}
// Usage Examples
func main() {
fmt.Println("=== Web Go Regex Pattern Matching Examples ===
")
// 1. Basic matching
fmt.Println("--- 1. Basic Pattern Matching ---")
fmt.Printf("Match pattern: %t
", MatchPattern("hello world", "hello"))
fmt.Printf("Find pattern: %s
", FindPattern("hello world", "\w+"))
// 2. Validation
fmt.Println("
--- 2. Validation ---")
fmt.Printf("Valid email: %t
", IsValidEmail("[email protected]"))
fmt.Printf("Valid URL: %t
", IsValidURL("https://example.com"))
fmt.Printf("Valid phone: %t
", IsValidPhoneNumber("+1-555-123-4567"))
fmt.Printf("Valid IP: %t
", IsValidIPAddress("192.168.1.1"))
fmt.Printf("Valid hex color: %t
", IsValidHexColor("#FF5733"))
// 3. Extraction
fmt.Println("
--- 3. Text Extraction ---")
text := "Contact us at [email protected] or [email protected]"
fmt.Printf("Extract emails: %v
", ExtractEmails(text))
fmt.Printf("Extract hashtags: %v
", ExtractHashtags("Hello #world #golang"))
// 4. Replace
fmt.Println("
--- 4. Search and Replace ---")
fmt.Printf("Replace pattern: %s
", ReplacePattern("hello world", "world", "Go"))
// 5. Group extraction
fmt.Println("
--- 5. Group Extraction ---")
dateText := "Date: 2025-12-31"
groups := ExtractGroups(dateText, `Date: (?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})`)
fmt.Printf("Extract groups: %v
", groups)
// 6. Advanced
fmt.Println("
--- 6. Advanced Patterns ---")
htmlText := "<p>Hello</p><p>World</p>"
contents := ExtractHTMLContent(htmlText, "p")
fmt.Printf("Extract HTML content: %v
", contents)
// 7. Analysis
fmt.Println("
--- 7. String Analysis ---")
fmt.Printf("Count occurrences: %d
", CountPatternOccurrences("hello hello world", "hello"))
fmt.Printf("Find whole word: %v
", FindWholeWord("hello world, hello!", "hello"))
// 8. Case insensitive
fmt.Println("
--- 8. Case Insensitive ---")
fmt.Printf("Find case insensitive: %v
", FindCaseInsensitive("Hello HELLO hello", "hello"))
fmt.Println("
=== All Regex Pattern Matching Examples Completed ===")
}
💻 Substituição de Strings go
🟡 intermediate
⭐⭐⭐
Buscar e substituir texto usando vários métodos incluindo substituição simples, substituição regex e funções personalizadas
⏱️ 25 min
🏷️ go, web, string processing, replacement
Prerequisites:
Intermediate Go, strings package, regexp package
// Web Go String Replacement Examples
// Using Go strings and regexp packages for text replacement
package main
import (
"fmt"
"regexp"
"strings"
)
// 1. Basic String Replacement
// ReplaceString replaces all occurrences of old with new
func ReplaceString(text, old, new string) string {
return strings.ReplaceAll(text, old, new)
}
// ReplaceStringN replaces first N occurrences
func ReplaceStringN(text, old, new string, n int) string {
return strings.Replace(text, old, new, n)
}
// ReplaceStringOnce replaces first occurrence
func ReplaceStringOnce(text, old, new string) string {
return strings.Replace(text, old, new, 1)
}
// 2. Case-Sensitive Replacement
// ReplaceCaseSensitive replaces with case sensitivity
func ReplaceCaseSensitive(text, old, new string) string {
return strings.ReplaceAll(text, old, new)
}
// ReplaceCaseInsensitive replaces ignoring case
func ReplaceCaseInsensitive(text, old, new string) string {
pattern := regexp.MustCompile((?i) + regexp.QuoteMeta(old))
return pattern.ReplaceAllString(text, new)
}
// 3. Regex Replacement
// ReplacePattern replaces pattern matches
func ReplacePattern(text, pattern, replacement string) string {
re := regexp.MustCompile(pattern)
return re.ReplaceAllString(text, replacement)
}
// ReplacePatternWithFunction replaces using a function
func ReplacePatternWithFunction(text, pattern string, repl func(string) string) string {
re := regexp.MustCompile(pattern)
return re.ReplaceAllStringFunc(text, repl)
}
// ReplaceWithCapturedGroups replaces using captured groups
func ReplaceWithCapturedGroups(text, pattern, template string) string {
re := regexp.MustCompile(pattern)
return re.ReplaceAllString(text, template)
}
// 4. Common Replacements
// ReplaceSpaces replaces multiple spaces with single space
func ReplaceSpaces(text string) string {
re := regexp.MustCompile("\s+")
return re.ReplaceAllString(text, " ")
}
// ReplaceNewlines replaces newlines with space
func ReplaceNewlines(text string) string {
return strings.ReplaceAll(text, "
", " ")
}
// ReplaceTabs replaces tabs with spaces
func ReplaceTabs(text, replacement string) string {
return strings.ReplaceAll(text, " ", replacement)
}
// ReplaceLineBreaks normalizes line breaks
func ReplaceLineBreaks(text string) string {
// Replace Windows line breaks with Unix
text = strings.ReplaceAll(text, "
", "
")
return text
}
// RemoveExtraWhitespace removes extra whitespace
func RemoveExtraWhitespace(text string) string {
// Replace multiple spaces with single space
re := regexp.MustCompile("\s+")
text = re.ReplaceAllString(text, " ")
// Trim leading/trailing whitespace
return strings.TrimSpace(text)
}
// 5. Text Cleanup
// RemoveSpecialChars removes special characters
func RemoveSpecialChars(text string) string {
re := regexp.MustCompile("[^a-zA-Z0-9\s]")
return re.ReplaceAllString(text, "")
}
// RemoveDigits removes digits from text
func RemoveDigits(text string) string {
re := regexp.MustCompile("\d")
return re.ReplaceAllString(text, "")
}
// RemoveLetters removes letters from text
func RemoveLetters(text string) string {
re := regexp.MustCompile("[a-zA-Z]")
return re.ReplaceAllString(text, "")
}
// RemovePunctuation removes punctuation
func RemovePunctuation(text string) string {
re := regexp.MustCompile("[[:punct:]]")
return re.ReplaceAllString(text, "")
}
// RemoveHTMLTags removes HTML tags
func RemoveHTMLTags(text string) string {
re := regexp.MustCompile("<[^>]*>")
return re.ReplaceAllString(text, "")
}
// RemoveURLs removes URLs from text
func RemoveURLs(text string) string {
re := regexp.MustCompile("https?://\S+")
return re.ReplaceAllString(text, "")
}
// RemoveEmails removes email addresses
func RemoveEmails(text string) string {
re := regexp.MustCompile("\S+@\S+\.\S+")
return re.ReplaceAllString(text, "")
}
// 6. Format Conversions
// ToSnakeCase converts to snake_case
func ToSnakeCase(text string) string {
// Insert underscore before capital letters
re := regexp.MustCompile("([a-z0-9])([A-Z])")
text = re.ReplaceAllString(text, "1_2")
// Convert to lowercase
return strings.ToLower(text)
}
// ToKebabCase converts to kebab-case
func ToKebabCase(text string) string {
re := regexp.MustCompile("([a-z0-9])([A-Z])")
text = re.ReplaceAllString(text, "1-2")
return strings.ToLower(text)
}
// ToCamelCase converts to camelCase
func ToCamelCase(text string) string {
// Split by underscore, dash, or space
re := regexp.MustCompile("[_\-]\s*")
words := re.Split(text, -1)
var result string
for i, word := range words {
if i == 0 {
result += strings.ToLower(word)
} else {
if len(word) > 0 {
result += strings.ToUpper(word[:1]) + strings.ToLower(word[1:])
}
}
}
return result
}
// ToPascalCase converts to PascalCase
func ToPascalCase(text string) string {
re := regexp.MustCompile("[_\-]\s*")
words := re.Split(text, -1)
var result string
for _, word := range words {
if len(word) > 0 {
result += strings.ToUpper(word[:1]) + strings.ToLower(word[1:])
}
}
return result
}
// ToTitleCase converts to Title Case
func ToTitleCase(text string) string {
re := regexp.MustCompile("\b\w")
return re.ReplaceAllStringFunc(text, func(s string) string {
return strings.ToUpper(s)
})
}
// 7. Advanced Replacements
// ReplaceBetween replaces text between two delimiters
func ReplaceBetween(text, start, end, replacement string) string {
pattern := regexp.MustCompile(start + ".*?" + end)
return pattern.ReplaceAllString(text, start+replacement+end)
}
// ReplaceRepeatedWords replaces repeated words
func ReplaceRepeatedWords(text string) string {
re := regexp.MustCompile("\b(\w+)\s+\1\b")
return re.ReplaceAllString(text, "1")
}
// ReplaceNumbers replaces numbers with text
func ReplaceNumbers(text, replacement string) string {
re := regexp.MustCompile("\d+")
return re.ReplaceAllString(text, replacement)
}
// ReplaceWithTemplate replaces using template values
func ReplaceWithTemplate(text string, values map[string]string) string {
result := text
for key, value := range values {
placeholder := fmt.Sprintf("{{%s}}", key)
result = strings.ReplaceAll(result, placeholder, value)
}
return result
}
// 8. Chain Replacements
// ChainReplace performs multiple replacements in sequence
func ChainReplace(text string, replacements []struct{ Old, New string }) string {
result := text
for _, repl := range replacements {
result = strings.ReplaceAll(result, repl.Old, repl.New)
}
return result
}
// ChainPatternReplace performs multiple pattern replacements
func ChainPatternReplace(text string, replacements []struct{ Pattern, Replacement string }) string {
result := text
for _, repl := range replacements {
re := regexp.MustCompile(repl.Pattern)
result = re.ReplaceAllString(result, repl.Replacement)
}
return result
}
// 9. Conditional Replacement
// ReplaceIfCondition replaces based on condition
func ReplaceIfCondition(text string, condition func(string) bool, old, new string) string {
if condition(text) {
return strings.ReplaceAll(text, old, new)
}
return text
}
// ReplaceAllMatching replaces all matches of a predicate
func ReplaceAllMatching(text string, predicate func(string) bool, replacement string) string {
words := strings.Fields(text)
for i, word := range words {
if predicate(word) {
words[i] = replacement
}
}
return strings.Join(words, " ")
}
// 10. Text Normalization
// NormalizeWhitespace normalizes all whitespace
func NormalizeWhitespace(text string) string {
// Replace all whitespace sequences with single space
re := regexp.MustCompile("\s+")
text = re.ReplaceAllString(text, " ")
return strings.TrimSpace(text)
}
// NormalizeQuotes normalizes quote characters
func NormalizeQuotes(text string) string {
// Replace smart quotes with regular quotes
text = strings.ReplaceAll(text, """, """)
text = strings.ReplaceAll(text, """, """)
text = strings.ReplaceAll(text, "'", "'")
text = strings.ReplaceAll(text, "'", "'")
return text
}
// NormalizeDashes normalizes dash characters
func NormalizeDashes(text string) string {
text = strings.ReplaceAll(text, "–", "-")
text = strings.ReplaceAll(text, "—", "--")
return text
}
// 11. Sanitization
// SanitizeFilename sanitizes filename
func SanitizeFilename(filename string) string {
// Replace invalid characters with underscore
re := regexp.MustCompile("[^a-zA-Z0-9._-]")
filename = re.ReplaceAllString(filename, "_")
// Remove multiple consecutive underscores
re = regexp.MustCompile("_+")
filename = re.ReplaceAllString(filename, "_")
return strings.Trim(filename, "_")
}
// SanitizePath sanitizes file path
func SanitizePath(path string) string {
// Remove invalid characters
re := regexp.MustCompile("[^a-zA-Z0-9/_-]")
path = re.ReplaceAllString(path, "")
// Replace multiple slashes
re = regexp.MustCompile("/+")
path = re.ReplaceAllString(path, "/")
return strings.Trim(path, "/")
}
// SanitizeHTML sanitizes HTML (basic)
func SanitizeHTML(html string) string {
// Remove script tags
re := regexp.MustCompile("<script[^>]*>.*?</script>")
html = re.ReplaceAllString(html, "")
// Remove style tags
re = regexp.MustCompile("<style[^>]*>.*?</style>")
html = re.ReplaceAllString(html, "")
return html
}
// Usage Examples
func main() {
fmt.Println("=== Web Go String Replacement Examples ===
")
// 1. Basic replacement
fmt.Println("--- 1. Basic Replacement ---")
fmt.Printf("Replace all: %s
", ReplaceString("hello world", "world", "Go"))
fmt.Printf("Replace once: %s
", ReplaceStringOnce("hello hello world", "hello", "Hi"))
// 2. Case replacement
fmt.Println("
--- 2. Case-Sensitive Replacement ---")
fmt.Printf("Case insensitive: %s
", ReplaceCaseInsensitive("Hello HELLO hello", "hello", "Hi"))
// 3. Pattern replacement
fmt.Println("
--- 3. Pattern Replacement ---")
fmt.Printf("Replace pattern: %s
", ReplacePattern("hello123world456", "\d+", "*"))
// 4. Common replacements
fmt.Println("
--- 4. Common Replacements ---")
fmt.Printf("Remove extra whitespace: '%s'
", RemoveExtraWhitespace("hello world test"))
fmt.Printf("Replace newlines: %s
", ReplaceNewlines("line1
line2
line3"))
// 5. Text cleanup
fmt.Println("
--- 5. Text Cleanup ---")
fmt.Printf("Remove special chars: %s
", RemoveSpecialChars("Hello, World! 123"))
fmt.Printf("Remove HTML tags: %s
", RemoveHTMLTags("<p>Hello</p>World"))
// 6. Format conversion
fmt.Println("
--- 6. Format Conversions ---")
fmt.Printf("To snake case: %s
", ToSnakeCase("HelloWorldGo"))
fmt.Printf("To kebab case: %s
", ToKebabCase("HelloWorldGo"))
fmt.Printf("To camel case: %s
", ToCamelCase("hello_world_go"))
fmt.Printf("To Pascal case: %s
", ToPascalCase("hello-world-go"))
fmt.Printf("To title case: %s
", ToTitleCase("hello world"))
// 7. Advanced replacements
fmt.Println("
--- 7. Advanced Replacements ---")
fmt.Printf("Replace between: %s
", ReplaceBetween("start[remove]end", "[", "]", "REPLACED"))
// 8. Template replacement
fmt.Println("
--- 8. Template Replacement ---")
template := "Hello {{name}}, welcome to {{place}}!"
values := map[string]string{"name": "John", "place": "Go"}
fmt.Printf("With template: %s
", ReplaceWithTemplate(template, values))
// 9. Normalization
fmt.Println("
--- 9. Normalization ---")
fmt.Printf("Normalize whitespace: '%s'
", NormalizeWhitespace("hello world
test"))
fmt.Printf("Sanitize filename: %s
", SanitizeFilename("file/name*.txt??"))
fmt.Println("
=== All String Replacement Examples Completed ===")
}