🎯 Recommended Samples
Balanced sample collections from various categories for you to explore
Android String Processing Kotlin Samples
Android Kotlin string processing examples including string split and join, regular expressions, and string replacement
💻 String Split and Join kotlin
🟢 simple
⭐⭐
Split strings by delimiters and join string collections with various separators
⏱️ 15 min
🏷️ kotlin, android, string processing
Prerequisites:
Basic Kotlin knowledge
// Android Kotlin String Split and Join Examples
// Kotlin standard library string operations
// 1. Basic String Splitting
class StringSplitter {
// Split by single delimiter
fun splitByDelimiter(text: String, delimiter: String): List<String> {
return text.split(delimiter)
}
// Split by multiple delimiters
fun splitByMultipleDelimiters(text: String, delimiters: List<String>): List<String> {
var result = listOf(text)
for (delimiter in delimiters) {
result = result.flatMap { it.split(delimiter) }
}
return result.filter { it.isNotEmpty() }
}
// Split by regex pattern
fun splitByRegex(text: String, pattern: String): List<String> {
val regex = Regex(pattern)
return text.split(regex)
}
// Split with limit
fun splitWithLimit(text: String, delimiter: String, limit: Int): List<String> {
return text.split(delimiter, limit = limit)
}
// Split into lines
fun splitIntoLines(text: String): List<String> {
return text.lines()
}
// Split by whitespace
fun splitByWhitespace(text: String): List<String> {
return text.split(Regex("\\s+"))
}
// Split and trim
fun splitAndTrim(text: String, delimiter: String): List<String> {
return text.split(delimiter)
.map { it.trim() }
.filter { it.isNotEmpty() }
}
}
// 2. String Joining
class StringJoiner {
// Join with delimiter
fun joinWithDelimiter(parts: List<String>, delimiter: String): String {
return parts.joinToString(delimiter)
}
// Join with prefix and suffix
fun joinWithPrefixSuffix(
parts: List<String>,
delimiter: String,
prefix: String,
suffix: String
): String {
return parts.joinToString(delimiter, prefix, suffix)
}
// Join with limit and truncated
fun joinWithLimit(
parts: List<String>,
delimiter: String,
limit: Int,
truncated: String
): String {
return parts.joinToString(
separator = delimiter,
limit = limit,
truncated = truncated
)
}
// Join with transformation
fun joinWithTransform(
parts: List<String>,
delimiter: String,
transform: (String) -> String
): String {
return parts.joinToString(delimiter) { transform(it) }
}
// Join non-null elements
fun joinNonNull(parts: List<String?>, delimiter: String): String {
return parts.filterNotNull().joinToString(delimiter)
}
// Join lines
fun joinLines(lines: List<String>): String {
return lines.joinToString("\\n")
}
// Join with index
fun joinWithIndex(parts: List<String>, delimiter: String): String {
return parts.mapIndexed { index, s -> "$index: $s" }
.joinToString(delimiter)
}
}
// 3. Advanced String Operations
class AdvancedStringOperations {
// Parse CSV line
fun parseCSVLine(line: String): List<String> {
return line.split(",").map { it.trim() }
}
// Parse key-value pairs
fun parseKeyValuePairs(text: String, pairDelimiter: String, kvDelimiter: String):
Map<String, String> {
return text.split(pairDelimiter)
.mapNotNull { pair ->
val parts = pair.split(kvDelimiter, limit = 2)
if (parts.size == 2) {
parts[0].trim() to parts[1].trim()
} else {
null
}
}
.toMap()
}
// Split and preserve delimiters
fun splitPreservingDelimiters(text: String, delimiters: List<String>): List<String> {
var result = text
val parts = mutableListOf<String>()
for (delimiter in delimiters) {
val temp = result.split(delimiter)
if (temp.size > 1) {
parts.addAll(temp.dropLast(1))
parts.add(delimiter)
result = temp.last()
}
}
parts.add(result)
return parts
}
// Word wrap
fun wordWrap(text: String, maxWidth: Int): List<String> {
val words = text.split(Regex("\\s+"))
val lines = mutableListOf<String>()
var currentLine = ""
for (word in words) {
val testLine = if (currentLine.isEmpty()) word else "$currentLine $word"
if (testLine.length <= maxWidth) {
currentLine = testLine
} else {
if (currentLine.isNotEmpty()) {
lines.add(currentLine)
}
currentLine = word
}
}
if (currentLine.isNotEmpty()) {
lines.add(currentLine)
}
return lines
}
}
// 4. String Builder for Efficient Building
class EfficientStringBuilder {
// Build string with StringBuilder
fun buildStringEfficiently(parts: List<String>): String {
return buildString {
for (part in parts) {
append(part)
append(" ")
}
}.trim()
}
// Build with conditional parts
fun buildWithConditionals(
base: String,
optional: String?,
condition: Boolean
): String {
return buildString {
append(base)
if (condition && optional != null) {
append(" ")
append(optional)
}
}
}
}
// Main demonstration
fun demonstrateStringSplitJoin() {
println("=== Android Kotlin String Split and Join Examples ===\n")
val splitter = StringSplitter()
// 1. Basic split
println("--- 1. Basic Split ---")
val text1 = "apple,banana,orange,grape"
val fruits = splitter.splitByDelimiter(text1, ",")
println("Split '$text1':")
fruits.forEach { println(" - $it") }
// 2. Split by multiple delimiters
println("\n--- 2. Split by Multiple Delimiters ---")
val text2 = "apple,banana;orange|grape"
val multiDelim = splitter.splitByMultipleDelimiters(text2, listOf(",", ";", "|"))
println("Split by [,,;,|]:")
multiDelim.forEach { println(" - $it") }
// 3. Split by regex
println("\n--- 3. Split by Regex ---")
val text3 = "apple123banana456orange"
val regexSplit = splitter.splitByRegex(text3, "\\d+")
println("Split by digits:")
regexSplit.forEach { println(" - $it") }
// 4. Split into lines
println("\n--- 4. Split into Lines ---")
val text4 = "Line 1\\nLine 2\\nLine 3"
val lines = splitter.splitIntoLines(text4)
println("Lines:")
lines.forEach { println(" - $it") }
// 5. Join with delimiter
println("\n--- 5. Join with Delimiter ---")
val joiner = StringJoiner()
val joined = joiner.joinWithDelimiter(fruits, " | ")
println("Joined with ' | ': $joined")
// 6. Join with prefix and suffix
println("\n--- 6. Join with Prefix/Suffix ---")
val joinedWithBrackets = joiner.joinWithPrefixSuffix(
fruits,
", ",
"[",
"]"
)
println("Joined with brackets: $joinedWithBrackets")
// 7. Join with limit
println("\n--- 7. Join with Limit ---")
val manyItems = (1..20).map { "Item$it" }
val joinedLimited = joiner.joinWithLimit(
manyItems,
", ",
limit = 5,
truncated = "..."
)
println("Limited join: $joinedLimited")
// 8. Parse CSV
println("\n--- 8. Parse CSV ---")
val advanced = AdvancedStringOperations()
val csvLine = "John,Doe,30,New York"
val parsedCSV = advanced.parseCSVLine(csvLine)
println("Parsed CSV:")
println(" Name: ${parsedCSV[0]} ${parsedCSV[1]}")
println(" Age: ${parsedCSV[2]}")
println(" City: ${parsedCSV[3]}")
// 9. Parse key-value pairs
println("\n--- 9. Parse Key-Value Pairs ---")
val kvText = "name=John;age=30;city=NYC"
val kvPairs = advanced.parseKeyValuePairs(kvText, ";", "=")
println("Parsed key-values:")
kvPairs.forEach { (key, value) ->
println(" $key: $value")
}
// 10. Word wrap
println("\n--- 10. Word Wrap ---")
val longText = "This is a very long text that needs to be wrapped into multiple lines"
val wrapped = advanced.wordWrap(longText, 20)
println("Wrapped text:")
wrapped.forEach { println(" $it") }
println("\n=== All String Split and Join Examples Completed ===")
}
💻 String Replacement kotlin
🟢 simple
⭐⭐⭐
Find and replace text using simple patterns, regex, and custom logic
⏱️ 20 min
🏷️ kotlin, android, string processing
Prerequisites:
Basic Kotlin knowledge
// Android Kotlin String Replacement Examples
// Kotlin standard library replacement methods
// 1. Basic String Replacement
class BasicReplacer {
// Replace single occurrence
fun replaceFirst(text: String, oldValue: String, newValue: String): String {
return text.replace(oldValue, newValue)
}
// Replace all occurrences (case-sensitive)
fun replaceAll(text: String, oldValue: String, newValue: String): String {
return text.replace(oldValue, newValue)
}
// Replace all occurrences (case-insensitive)
fun replaceAllIgnoreCase(text: String, oldValue: String, newValue: String): String {
return text.replace(Regex(oldValue, RegexOption.IGNORE_CASE), newValue)
}
// Replace first N occurrences
fun replaceFirstN(text: String, oldValue: String, newValue: String, n: Int): String {
var count = 0
var result = text
var index = result.indexOf(oldValue)
while (index != -1 && count < n) {
result = result.substring(0, index) + newValue +
result.substring(index + oldValue.length)
count++
index = result.indexOf(oldValue)
}
return result
}
// Replace after index
fun replaceAfterIndex(
text: String,
oldValue: String,
newValue: String,
startIndex: Int
): String {
val before = text.substring(0, startIndex)
val after = text.substring(startIndex)
return before + after.replace(oldValue, newValue)
}
}
// 2. Regex-Based Replacement
class RegexReplacer {
// Replace using regex pattern
fun replaceByPattern(text: String, pattern: String, replacement: String): String {
val regex = Regex(pattern)
return text.replace(regex, replacement)
}
// Replace digits with placeholder
fun replaceDigits(text: String, replacement: String): String {
return text.replace(Regex("\\d"), replacement)
}
// Replace multiple spaces with single space
fun replaceMultipleSpaces(text: String): String {
return text.replace(Regex("\\s+"), " ")
}
// Replace HTML tags
fun replaceHTMLTags(text: String, replacement: String): String {
return text.replace(Regex("<[^>]*>"), replacement)
}
// Replace email with masked version
fun replaceEmailWithMask(text: String): String {
return text.replace(
Regex("([A-Za-z0-9])[A-Za-z0-9+_.-]+(@[A-Za-z0-9.-]+)"),
"$1***$2"
)
}
// Replace using callback/transform
fun replaceWithTransform(text: String, pattern: String, transform: (MatchResult) -> String): String {
val regex = Regex(pattern)
return text.replace(regex) { match -> transform(match) }
}
// Replace numbers with their doubled value
fun replaceNumbersWithDouble(text: String): String {
return text.replace(Regex("\\d+")) { match ->
val num = match.value.toInt()
(num * 2).toString()
}
}
// Replace words in brackets with uppercase
fun replaceBracketedWithUppercase(text: String): String {
return text.replace(Regex("\\[(\\w+)\\]")) { match ->
match.groupValues[1].uppercase()
}
}
}
// 3. Conditional Replacement
class ConditionalReplacer {
// Replace if string contains pattern
fun replaceIfContains(
text: String,
condition: String,
oldValue: String,
newValue: String
): String {
return if (condition in text) {
text.replace(oldValue, newValue)
} else {
text
}
}
// Replace only whole words
fun replaceWholeWords(text: String, word: String, replacement: String): String {
val pattern = Regex("\\b$word\\b")
return text.replace(pattern, replacement)
}
// Replace only at start of string
fun replaceAtStart(text: String, prefix: String, replacement: String): String {
return if (text.startsWith(prefix)) {
replacement + text.substring(prefix.length)
} else {
text
}
}
// Replace only at end of string
fun replaceAtEnd(text: String, suffix: String, replacement: String): String {
return if (text.endsWith(suffix)) {
text.substring(0, text.length - suffix.length) + replacement
} else {
text
}
}
// Replace between delimiters
fun replaceBetweenDelimiters(
text: String,
startDelim: String,
endDelim: String,
replacement: String
): String {
val pattern = Regex("$startDelim.*?$endDelim")
return text.replace(pattern, "$startDelim$replacement$endDelim")
}
}
// 4. Template-Based Replacement
class TemplateReplacer {
// Replace placeholders in template
fun replacePlaceholders(template: String, data: Map<String, String>): String {
var result = template
for ((key, value) in data) {
result = result.replace("{{$key}}", value)
}
return result
}
// Replace with default values
fun replaceWithDefaults(
template: String,
data: Map<String, String>,
defaults: Map<String, String>
): String {
var result = template
for ((key, defaultValue) in defaults) {
val value = data[key] ?: defaultValue
result = result.replace("{{$key}}", value)
}
return result
}
// Replace using function
fun replaceUsingFunction(
template: String,
placeholder: String,
supplier: (String) -> String
): String {
val pattern = Regex("\\{$placeholder\\}")
return template.replace(pattern) { supplier(placeholder) }
}
}
// 5. Advanced Replacement Operations
class AdvancedReplacer {
// Replace with word count
fun replaceWithWordCount(text: String, target: String): String {
val words = text.split(Regex("\\s+"))
val count = words.count { it.equals(target, ignoreCase = true) }
return text.replace(target, "$target($count)")
}
// Swap two words
fun swapWords(text: String, word1: String, word2: String): String {
return text
.replace(word1, "\u0000")
.replace(word2, word1)
.replace("\u0000", word2)
}
// Replace consecutive duplicates
fun replaceConsecutiveDuplicates(text: String, replacement: String): String {
return text.replace(Regex("\\b(\\w+)\\s+\\1\\b"), replacement)
}
// Replace with incrementing numbers
fun replaceWithNumbers(text: String, placeholder: String): String {
var counter = 1
return text.replace(Regex(placeholder)) {
counter++.toString()
}
}
// Chain multiple replacements
fun chainReplacements(text: String, replacements: List<Pair<String, String>>): String {
var result = text
for ((old, new) in replacements) {
result = result.replace(old, new)
}
return result
}
// Replace in reverse order
fun replaceFromEnd(text: String, oldValue: String, newValue: String): String {
val lastIndex = text.lastIndexOf(oldValue)
return if (lastIndex != -1) {
text.substring(0, lastIndex) + newValue +
text.substring(lastIndex + oldValue.length)
} else {
text
}
}
}
// 6. Sanitization and Cleaning
class StringSanitizer {
// Remove profanity (simple version)
fun sanitizeProfanity(text: String, badWords: Set<String>): String {
var result = text
for (word in badWords) {
val pattern = Regex("\\b${word}\\b", RegexOption.IGNORE_CASE)
result = result.replace(pattern) { match ->
"*".repeat(match.value.length)
}
}
return result
}
// Clean user input
fun cleanUserInput(text: String): String {
return text
.replace(Regex("<[^>]*>"), "") // Remove HTML
.replace(Regex("\\s+"), " ") // Normalize whitespace
.trim()
}
// Sanitize filename
fun sanitizeFileName(name: String): String {
val invalidChars = setOf('/', '\\', ':', '*', '?', '"', '<', '>', '|')
var result = name
for (char in invalidChars) {
result = result.replace(char.toString(), "_")
}
return result
}
// Escape special characters
fun escapeSpecialChars(text: String): String {
return text
.replace("\\", "\\\\")
.replace(""", "\\"")
.replace("'", "\\'")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\t", "\\t")
}
}
// Main demonstration
fun demonstrateStringReplacement() {
println("=== Android Kotlin String Replacement Examples ===\n")
val replacer = BasicReplacer()
// 1. Basic replacement
println("--- 1. Basic Replacement ---")
val text1 = "Hello World, World is great"
val replaced = replacer.replaceAll(text1, "World", "Kotlin")
println("Original: $text1")
println("Replaced: $replaced")
// 2. Case-insensitive replacement
println("\n--- 2. Case-Insensitive Replacement ---")
val text2 = "Hello world, WORLD, World"
val caseReplaced = replacer.replaceAllIgnoreCase(text2, "world", "There")
println("Original: $text2")
println("Replaced: $caseReplaced")
// 3. Regex replacement
println("\n--- 3. Regex Replacement ---")
val regexReplacer = RegexReplacer()
val text3 = "Phone: 123-456-7890"
val masked = regexReplacer.replaceDigits(text3, "X")
println("Original: $text3")
println("Digits masked: $masked")
// 4. Replace with transform
println("\n--- 4. Replace with Transform ---")
val text4 = "Values: 10, 20, 30"
val doubled = regexReplacer.replaceNumbersWithDouble(text4)
println("Original: $text4")
println("Numbers doubled: $doubled")
// 5. Whole word replacement
println("\n--- 5. Whole Word Replacement ---")
val condReplacer = ConditionalReplacer()
val text5 = "cat catalog category cat"
val wholeReplaced = condReplacer.replaceWholeWords(text5, "cat", "dog")
println("Original: $text5")
println("Whole word replaced: $wholeReplaced")
// 6. Template replacement
println("\n--- 6. Template Replacement ---")
val templateReplacer = TemplateReplacer()
val template = "Hello {name}, your order {order} is ready"
val data = mapOf("name" to "John", "order" to "#12345")
val filled = templateReplacer.replacePlaceholders(template, data)
println("Template: $template")
println("Filled: $filled")
// 7. Advanced replacement
println("\n--- 7. Advanced Replacement ---")
val advanced = AdvancedReplacer()
val text7 = "Item1, Item2, Item3"
val numbered = advanced.replaceWithNumbers(text7, "Item\\d+")
println("Original: $text7")
println("Numbered: $numbered")
// 8. Swap words
println("\n--- 8. Swap Words ---")
val text8 = "I like apples and oranges"
val swapped = advanced.swapWords(text8, "apples", "oranges")
println("Original: $text8")
println("Swapped: $swapped")
// 9. Sanitization
println("\n--- 9. Sanitization ---")
val sanitizer = StringSanitizer()
val text9 = "Hello<script>alert('xss')</script> World"
val clean = sanitizer.cleanUserInput(text9)
println("Original: $text9")
println("Cleaned: $clean")
val badFile = "file:name?.txt"
println("\nInvalid filename: $badFile")
println("Sanitized: ${sanitizer.sanitizeFileName(badFile)}")
// 10. Masking
println("\n--- 10. Email Masking ---")
val text10 = "Contact us at [email protected] for help"
val masked = regexReplacer.replaceEmailWithMask(text10)
println("Original: $text10")
println("Masked: $masked")
println("\n=== All String Replacement Examples Completed ===")
}
💻 Regular Expressions kotlin
🟡 intermediate
⭐⭐⭐⭐
Pattern matching, validation, search, and replace using regular expressions
⏱️ 25 min
🏷️ kotlin, android, string processing, regex
Prerequisites:
Intermediate Kotlin, Regex basics
// Android Kotlin Regular Expression Examples
// Kotlin standard library regex support
import java.util.regex.Pattern
import java.util.regex.Matcher
// 1. Basic Pattern Matching
class RegexMatcher {
// Check if pattern matches entire string
fun matchesFullString(text: String, pattern: String): Boolean {
val regex = Regex(pattern)
return regex.matches(text)
}
// Check if pattern contains in string
fun containsPattern(text: String, pattern: String): Boolean {
val regex = Regex(pattern)
return regex.containsMatchIn(text)
}
// Find first match
fun findFirstMatch(text: String, pattern: String): MatchResult? {
val regex = Regex(pattern)
return regex.find(text)
}
// Find all matches
fun findAllMatches(text: String, pattern: String): List<MatchResult> {
val regex = Regex(pattern)
return regex.findAll(text).toList()
}
// Find matches with groups
fun findGroupMatches(text: String, pattern: String): List<List<String>> {
val regex = Regex(pattern)
return regex.findAll(text).map { match ->
match.groupValues
}.toList()
}
}
// 2. Common Validation Patterns
class StringValidator {
// Validate email
fun isValidEmail(email: String): Boolean {
val emailPattern = Regex("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$")
return emailPattern.matches(email)
}
// Validate phone number
fun isValidPhoneNumber(phone: String): Boolean {
val phonePattern = Regex("^\\+?[1-9]\\d{1,14}$")
return phonePattern.matches(phone)
}
// Validate URL
fun isValidURL(url: String): Boolean {
val urlPattern = Regex(
"^https?://[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}(/[^\\s]*)?$"
)
return urlPattern.matches(url)
}
// Validate IPv4 address
fun isValidIPv4(ip: String): Boolean {
val ipPattern = Regex(
"^((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 ipPattern.matches(ip)
}
// Validate credit card (Luhn algorithm placeholder)
fun isValidCreditCard(card: String): Boolean {
val cardPattern = Regex("^\\d{13,19}$")
return cardPattern.matches(card.replace("\\s", ""))
}
// Validate hexadecimal color
fun isValidHexColor(color: String): Boolean {
val colorPattern = Regex("^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$")
return colorPattern.matches(color)
}
// Validate strong password
fun isStrongPassword(password: String): Boolean {
// At least 8 chars, 1 uppercase, 1 lowercase, 1 digit, 1 special
val passwordPattern = Regex(
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$"
)
return passwordPattern.matches(password)
}
// Validate date format (YYYY-MM-DD)
fun isValidDate(date: String): Boolean {
val datePattern = Regex("^\\d{4}-\\d{2}-\\d{2}$")
return datePattern.matches(date)
}
// Validate username (alphanumeric, underscore, 3-20 chars)
fun isValidUsername(username: String): Boolean {
val usernamePattern = Regex("^[a-zA-Z0-9_]{3,20}$")
return usernamePattern.matches(username)
}
// Validate postal code (US format)
fun isValidPostalCode(code: String): Boolean {
val postalPattern = Regex("^\\d{5}(-\\d{4})?$")
return postalPattern.matches(code)
}
}
// 3. Search and Extract
class RegexSearcher {
// Extract all email addresses
fun extractEmails(text: String): List<String> {
val emailPattern = Regex("[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}")
return emailPattern.findAll(text).map { it.value }.toList()
}
// Extract all URLs
fun extractURLs(text: String): List<String> {
val urlPattern = Regex("https?://[^\\s]+")
return urlPattern.findAll(text).map { it.value }.toList()
}
// Extract all hashtags
fun extractHashtags(text: String): List<String> {
val hashtagPattern = Regex("#\\w+")
return hashtagPattern.findAll(text).map { it.value }.toList()
}
// Extract all mentions
fun extractMentions(text: String): List<String> {
val mentionPattern = Regex("@\\w+")
return mentionPattern.findAll(text).map { it.value }.toList()
}
// Extract numbers
fun extractNumbers(text: String): List<Double> {
val numberPattern = Regex("-?\\d+\\.\\d+|-?\\d+")
return numberPattern.findAll(text).map { it.value.toDouble() }.toList()
}
// Extract dates in various formats
fun extractDates(text: String): List<String> {
val datePattern = Regex(
"\\d{4}-\\d{2}-\\d{2}|\\d{2}/\\d{2}/\\d{4}|\\d{2}\\.\\d{2}\\.\\d{4}"
)
return datePattern.findAll(text).map { it.value }.toList()
}
// Extract words starting with capital
fun extractCapitalizedWords(text: String): List<String> {
val capitalizedPattern = Regex("\\b[A-Z][a-z]+\\b")
return capitalizedPattern.findAll(text).map { it.value }.toList()
}
// Extract quoted text
fun extractQuotedText(text: String): List<String> {
val quotePattern = Regex(""([^"]*)"")
return quotePattern.findAll(text).map { it.groupValues[1] }.toList()
}
}
// 4. Text Processing with Regex
class RegexTextProcessor {
// Remove extra whitespace
fun normalizeWhitespace(text: String): String {
return text.replace(Regex("\\s+"), " ").trim()
}
// Remove all special characters
fun removeSpecialChars(text: String): String {
return text.replace(Regex("[^A-Za-z0-9\\s]"), "")
}
// Remove all digits
fun removeDigits(text: String): String {
return text.replace(Regex("\\d"), "")
}
// Remove HTML tags
fun removeHTMLTags(text: String): String {
return text.replace(Regex("<[^>]*>"), "")
}
// Mask email (keep first 2 chars of local part)
fun maskEmail(email: String): String {
val emailPattern = Regex("^([A-Za-z0-9]{2})[A-Za-z0-9+_.-]+(@[A-Za-z0-9.-]+)")
return email.replace(emailPattern, "$1***$2")
}
// Mask credit card (show only last 4 digits)
fun maskCreditCard(card: String): String {
val cleanCard = card.replace("\\s", "")
if (cleanCard.length >= 4) {
val last4 = cleanCard.takeLast(4)
return "*".repeat(cleanCard.length - 4) + last4
}
return card
}
// Format phone number
fun formatPhoneNumber(phone: String): String {
val cleanPhone = phone.replace(Regex("[^\\d]"), "")
return when {
cleanPhone.length == 10 ->
"(${cleanPhone.substring(0, 3)}) ${cleanPhone.substring(3, 6)}-${cleanPhone.substring(6)}"
cleanPhone.length == 11 && cleanPhone.startsWith("1") ->
"+1 (${cleanPhone.substring(1, 4)}) ${cleanPhone.substring(4, 7)}-${cleanPhone.substring(7)}"
else -> phone
}
}
}
// 5. Advanced Pattern Matching
class AdvancedPatternMatcher {
// Find repeated words
fun findRepeatedWords(text: String): List<Pair<String, Int>> {
val wordPattern = Regex("\\b(\\w+)\\b(?:\\s+\\b\\1\\b)+", RegexOption.IGNORE_CASE)
return wordPattern.findAll(text).map { match ->
match.groupValues[1] to match.value.split(Regex("\\s+")).size
}.toList()
}
// Find palindromes
fun findPalindromes(text: String): List<String> {
val wordPattern = Regex("\\b[a-zA-Z]+\\b")
return wordPattern.findAll(text)
.map { it.value }
.filter { word -> word.equals(word.reversed(), ignoreCase = true) }
.toList()
}
// Validate and extract JSON-like key-value
fun extractJSONPairs(text: String): Map<String, String> {
val jsonPattern = Regex(""([^"]+)":\\s*"([^"]*)"")
return jsonPattern.findAll(text).associate { match ->
match.groupValues[1] to match.groupValues[2]
}
}
// Find words with specific pattern (e.g., starts and ends with same letter)
fun findSameStartEnd(text: String): List<String> {
val wordPattern = Regex("\\b([a-z])\\w*\\1\\b", RegexOption.IGNORE_CASE)
return wordPattern.findAll(text).map { it.value }.toList()
}
}
// Main demonstration
fun demonstrateRegexPatterns() {
println("=== Android Kotlin Regular Expression Examples ===\n")
val matcher = RegexMatcher()
// 1. Basic matching
println("--- 1. Basic Pattern Matching ---")
val text1 = "The price is $19.99"
println("Contains price: ${matcher.containsPattern(text1, "\\\\$\\d+\\.\\d{2}")}")
// 2. Email validation
println("\n--- 2. Email Validation ---")
val validator = StringValidator()
val emails = listOf(
"[email protected]",
"invalid.email",
"[email protected]"
)
emails.forEach { email ->
println("'$email' valid: ${validator.isValidEmail(email)}")
}
// 3. Password strength
println("\n--- 3. Password Strength ---")
val passwords = listOf(
"weak",
"Strong1!",
"StrongPass123!"
)
passwords.forEach { pass ->
println("'$pass' strong: ${validator.isStrongPassword(pass)}")
}
// 4. Extract data
println("\n--- 4. Extract Data from Text ---")
val sampleText = """
Contact us at [email protected] or [email protected].
Visit https://example.com or http://test.org for more info.
Mention @user1 and @user2 in your posts.
Use #hashtag1 and #hashtag2.
""".trimIndent()
val searcher = RegexSearcher()
println("Emails found:")
searcher.extractEmails(sampleText).forEach { println(" - $it") }
println("\nURLs found:")
searcher.extractURLs(sampleText).forEach { println(" - $it") }
println("\nMentions found:")
searcher.extractMentions(sampleText).forEach { println(" - $it") }
println("\nHashtags found:")
searcher.extractHashtags(sampleText).forEach { println(" - $it") }
// 5. Text processing
println("\n--- 5. Text Processing ---")
val processor = RegexTextProcessor()
val messyText = " This has extra spaces "
println("Original: '$messyText'")
println("Normalized: '${processor.normalizeWhitespace(messyText)}'")
val htmlText = "<p>Hello <b>World</b></p>"
println("\nHTML: '$htmlText'")
println("Removed tags: '${processor.removeHTMLTags(htmlText)}'")
// 6. Masking
println("\n--- 6. Data Masking ---")
val email = "[email protected]"
println("Original: $email")
println("Masked: ${processor.maskEmail(email)}")
val card = "1234 5678 9012 3456"
println("\nCard: $card")
println("Masked: ${processor.maskCreditCard(card)}")
// 7. Advanced patterns
println("\n--- 7. Advanced Patterns ---")
val advanced = AdvancedPatternMatcher()
val repeatedText = "This is is a test test of repeated words"
println("\nText: '$repeatedText'")
println("Repeated words:")
advanced.findRepeatedWords(repeatedText).forEach { (word, count) ->
println(" - '$word' appears $count times consecutively")
}
val palindromeText = "Did you see that racecar level mom?"
println("\nText: '$palindromeText'")
println("Palindromes found:")
advanced.findPalindromes(palindromeText).forEach { println(" - $it") }
println("\n=== All Regular Expression Examples Completed ===")
}