Elysia Tools

Explora herramientas, ejemplos, explicaciones visuales y guías temáticas en un solo espacio claro.

Categorías populares

Temas

Idioma
ZHESPTRUFRDEEN

Elysia Tools

Navegación

Go

Ejemplos de Procesamiento de Cadenas Web Go

Ejemplos de procesamiento de cadenas Web Go incluyendo división/unión de cadenas, expresiones regulares y reemplazo de cadenas

Ejemplos

Entradas de esta colección

CódigogoSimple

División/Unión de Cadenas

Dividir cadenas por separadores y unir sectores de cadenas usando el paquete strings de Go

Dificultad

3/10

Tiempo estimado

20 min

Etiquetas

go, web, string processing

Requisitos previos

Basic Go, strings package

go
// 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 ===")
}
CódigogoIntermedio

Coincidencia de Patrones Regex

Usar expresiones regulares para coincidencia de patrones, validación y búsqueda de texto con el paquete regexp de Go

Dificultad

6/10

Tiempo estimado

30 min

Etiquetas

go, web, string processing, regex

Requisitos previos

Intermediate Go, regexp package, regex syntax

go
// 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("test@example.com"))
	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 ===")
}
CódigogoIntermedio

Reemplazo de Cadenas

Buscar y reemplazar texto usando varios métodos incluyendo reemplazo simple, reemplazo regex y funciones personalizadas

Dificultad

5/10

Tiempo estimado

25 min

Etiquetas

go, web, string processing, replacement

Requisitos previos

Intermediate Go, strings package, regexp package

go
// 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 ===")
}

Herramientas

Herramientas que suelen usarse con este ejemplo

Relacionado

Colecciones de ejemplos relacionadas

Guía de uso de la herramienta

Contexto para entender esta colección de ejemplos

Título

Ejemplos de Procesamiento de Cadenas Web Go

Descripción

Ejemplos de procesamiento de cadenas Web Go incluyendo división/unión de cadenas, expresiones regulares y reemplazo de cadenas

Resumen

Ejemplos de procesamiento de cadenas Web Go incluyendo división/unión de cadenas, expresiones regulares y reemplazo de cadenas

Cuándo usarlo

  • Use this sample set when you want reference inputs for Ejemplos de Procesamiento de Cadenas Web Go.
  • Use it to preview output formats and compare related sample variants.

Cómo funciona

  1. 1Open a sample entry to inspect the prepared example payload or asset.
  2. 2Compare it with related tools to understand how the workflow connects.

Casos de uso

  • División/Unión de Cadenas
  • Coincidencia de Patrones Regex
  • Reemplazo de Cadenas

Preguntas frecuentes

What is included in Ejemplos de Procesamiento de Cadenas Web Go?

This page includes curated sample entries, related tools, and neighboring sample collections for Ejemplos de Procesamiento de Cadenas Web Go.

Inicio
Herramientas3197
Ejemplos593
Visualizaciones461
Visores de archivos103
Temas229
Etiquetas333
Imágenes, audio y video655

Herramientas de procesamiento, conversión y optimización de imágenes, audio y video

Matemáticas, fechas y finanzas644

Calculadoras, herramientas numéricas, lógica de fechas, estadística y finanzas

Diseño y color296

Herramientas de color, maquetación, gráficos, estilo visual y apoyo al diseño

Texto y redacción209

Herramientas de redacción, limpieza, formato, extracción y análisis de texto

Desarrollo y Web193

Utilidades para desarrolladores, red, depuración web y automatización

Conversión y codificación175

Herramientas de conversión de formatos, archivos, unidades, archivos comprimidos y codificación

Estructurar una captura de interfaz, revisarla y entregarla a desarrollo
Boceto de piano, revisión MIDI y entrega de una maqueta de escucha
Revisión de texturas retro y entrega de recursos
Revisión y entrega de guías de procedimiento con capturas
Revisión visual de un rediseño adaptable y entrega de evidencias

© 2026 Elysia Tools. Todos los derechos reservados.

DocumentaciónPreciosAcerca deTérminos de servicioPolítica de privacidadCookiesContacto

Development

Generador de Cadenas Regex

Genera cadenas aleatorias que coinciden con un patrón de expresión regular

Text Processing

Contiene Cadena

Comprueba si una cadena contiene subcadenas o caracteres específicos

Utilities

Reemplazador de Archivos de Texto

Buscar y reemplazar texto en archivos con soporte para regex, múltiples patrones y creación de respaldos

Format Conversion

Convertidor Hex a Texto

Convierte texto hacia/desde cadenas hexadecimales con espaciado, prefijo (0x/\x/U+) y opciones de mayúsculas/minúsculas flexibles

Generator

Generador de Cadenas Aleatorias

Genera cadenas aleatorias con conjuntos de caracteres, longitud y patrones personalizables

Development

Depurador de Regex

Recorre cómo una expresión regular coincide con una cadena posición por posición: visualiza intentos de coincidencia, éxitos parciales, retrocesos y capturas — una herramienta para entender el comportamiento de regex, no solo el resultado final

Development

Vista Previa de Reemplazo Regex

Vista previa en tiempo real de reemplazos regex con resaltado de diferencias y estadísticas

Development

Probador de Regex

Prueba expresiones regulares contra texto

Swift

Ejemplos de Procesamiento de Cadenas macOS Swift

Ejemplos de procesamiento de cadenas macOS Swift incluyendo dividir/unir, expresiones regulares y reemplazo de cadenas

Python

Ejemplos de Procesamiento de Cadenas Web Python

Ejemplos de procesamiento de cadenas Web Python incluyendo división/unión de cadenas, expresiones regulares y reemplazo de cadenas

Rust

Ejemplos de Procesamiento de Cadenas Web Rust

Ejemplos de procesamiento de cadenas Web Rust incluyendo dividir/unir cadenas, regex y operaciones de reemplazo

TypeScript

Ejemplos de Procesamiento de Cadenas Web TypeScript

Ejemplos de procesamiento de cadenas Web TypeScript incluyendo manipulación de cadenas, coincidencia de patrones y transformación de texto

C++

Procesamiento de Cadenas Windows - Ejemplos C++

Ejemplos completos de procesamiento de cadenas en C++ para plataforma Windows incluyendo concatenación, expresiones regulares y operaciones de reemplazo

Java

Ejemplos de Procesamiento de Cadenas Android Java

Ejemplos de procesamiento de cadenas Android Java incluyendo división y unión de cadenas, expresiones regulares y reemplazo de cadenas