🎯 Exemples recommandés
Balanced sample collections from various categories for you to explore
Exemples de Traitement de Chaînes Android Java
Exemples de traitement de chaînes Android Java incluant division et jointure de chaînes, expressions régulières et remplacement de chaînes
💻 Division et Jointure de Chaînes java
🟢 simple
⭐⭐
Diviser les chaînes par délimiteurs et joindre des collections de chaînes avec divers séparateurs
⏱️ 15 min
🏷️ java, android, string processing
Prerequisites:
Basic Java knowledge
// Android Java String Split and Join Examples
// Java standard library string operations
import java.util.*;
import java.util.stream.Collectors;
// 1. Basic String Splitting
public class StringSplitter {
// Split by single delimiter
public String[] splitByDelimiter(String text, String delimiter) {
return text.split(delimiter);
}
// Split by multiple delimiters
public String[] splitByMultipleDelimiters(String text, String[] delimiters) {
String result = text;
for (String delimiter : delimiters) {
result = result.replace(delimiter, " ");
}
return result.trim().split("\\s+");
}
// Split by regex pattern
public String[] splitByRegex(String text, String pattern) {
return text.split(pattern);
}
// Split with limit
public String[] splitWithLimit(String text, String delimiter, int limit) {
return text.split(delimiter, limit);
}
// Split into lines
public String[] splitIntoLines(String text) {
return text.split("\\r?\\n");
}
// Split by whitespace
public String[] splitByWhitespace(String text) {
return text.trim().split("\\s+");
}
// Split and trim
public String[] splitAndTrim(String text, String delimiter) {
String[] parts = text.split(delimiter);
List<String> result = new ArrayList<>();
for (String part : parts) {
String trimmed = part.trim();
if (!trimmed.isEmpty()) {
result.add(trimmed);
}
}
return result.toArray(new String[0]);
}
}
// 2. String Joining
public class StringJoiner {
// Join with delimiter
public String joinWithDelimiter(String[] parts, String delimiter) {
return String.join(delimiter, parts);
}
// Join list with delimiter
public String joinList(List<String> parts, String delimiter) {
return String.join(delimiter, parts);
}
// Join with prefix and suffix using StringJoiner
public String joinWithPrefixSuffix(String[] parts, String delimiter, String prefix, String suffix) {
StringJoiner joiner = new StringJoiner(delimiter, prefix, suffix);
for (String part : parts) {
joiner.add(part);
}
return joiner.toString();
}
// Join with transformation
public String joinWithTransform(List<Integer> numbers, String delimiter) {
return numbers.stream()
.map(String::valueOf)
.collect(Collectors.joining(delimiter));
}
// Join non-null elements
public String joinNonNull(List<String> parts, String delimiter) {
List<String> nonNull = new ArrayList<>();
for (String part : parts) {
if (part != null) {
nonNull.add(part);
}
}
return String.join(delimiter, nonNull);
}
// Join lines
public String joinLines(String[] lines) {
return String.join("\\n", lines);
}
// Join with index
public String joinWithIndex(String[] parts, String delimiter) {
List<String> withIndex = new ArrayList<>();
for (int i = 0; i < parts.length; i++) {
withIndex.add(i + ": " + parts[i]);
}
return String.join(delimiter, withIndex);
}
}
// 3. Advanced String Operations
public class AdvancedStringOperations {
// Parse CSV line
public String[] parseCSVLine(String line) {
String[] parts = line.split(",");
String[] result = new String[parts.length];
for (int i = 0; i < parts.length; i++) {
result[i] = parts[i].trim();
}
return result;
}
// Parse key-value pairs
public Map<String, String> parseKeyValuePairs(String text, String pairDelimiter, String kvDelimiter) {
Map<String, String> result = new HashMap<>();
String[] pairs = text.split(pairDelimiter);
for (String pair : pairs) {
String[] parts = pair.split(kvDelimiter, 2);
if (parts.length == 2) {
result.put(parts[0].trim(), parts[1].trim());
}
}
return result;
}
// Word wrap
public String[] wordWrap(String text, int maxWidth) {
String[] words = text.split("\\s+");
List<String> lines = new ArrayList<>();
StringBuilder currentLine = new StringBuilder();
for (String word : words) {
String testLine = currentLine.length() == 0 ? word : currentLine + " " + word;
if (testLine.length() <= maxWidth) {
currentLine = new StringBuilder(testLine);
} else {
if (currentLine.length() > 0) {
lines.add(currentLine.toString());
}
currentLine = new StringBuilder(word);
}
}
if (currentLine.length() > 0) {
lines.add(currentLine.toString());
}
return lines.toArray(new String[0]);
}
// Capitalize first letter
public String capitalize(String text) {
if (text == null || text.isEmpty()) {
return text;
}
return Character.toUpperCase(text.charAt(0)) + text.substring(1);
}
// Capitalize all words
public String capitalizeWords(String text) {
String[] words = text.split("\\s+");
StringBuilder result = new StringBuilder();
for (int i = 0; i < words.length; i++) {
if (i > 0) {
result.append(" ");
}
if (!words[i].isEmpty()) {
result.append(Character.toUpperCase(words[i].charAt(0)));
if (words[i].length() > 1) {
result.append(words[i].substring(1).toLowerCase());
}
}
}
return result.toString();
}
// Reverse string
public String reverse(String text) {
return new StringBuilder(text).reverse().toString();
}
// Count occurrences
public int countOccurrences(String text, String substring) {
int count = 0;
int index = 0;
while ((index = text.indexOf(substring, index)) != -1) {
count++;
index += substring.length();
}
return count;
}
}
// 4. String Builder for Efficient Building
public class EfficientStringBuilder {
// Build string with StringBuilder
public String buildStringEfficiently(String[] parts) {
StringBuilder sb = new StringBuilder();
for (String part : parts) {
sb.append(part).append(" ");
}
return sb.toString().trim();
}
// Build with conditional parts
public String buildWithConditionals(String base, String optional, boolean includeOptional) {
StringBuilder sb = new StringBuilder();
sb.append(base);
if (includeOptional && optional != null) {
sb.append(" ").append(optional);
}
return sb.toString();
}
// Build with loop
public String buildWithLoop(List<String> items, String separator) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
if (i > 0) {
sb.append(separator);
}
sb.append(items.get(i));
}
return sb.toString();
}
// Build with formatted values
public String buildWithFormat(String template, Object... args) {
return String.format(template, args);
}
}
// 5. String Utilities
public class StringUtils {
// Check if string is empty or null
public boolean isEmpty(String text) {
return text == null || text.isEmpty();
}
// Check if string is blank (empty or whitespace only)
public boolean isBlank(String text) {
return text == null || text.trim().isEmpty();
}
// Truncate string
public String truncate(String text, int maxLength) {
if (text == null || text.length() <= maxLength) {
return text;
}
return text.substring(0, maxLength);
}
// Truncate with suffix
public String truncateWithSuffix(String text, int maxLength, String suffix) {
if (text == null || text.length() <= maxLength) {
return text;
}
return text.substring(0, maxLength - suffix.length()) + suffix;
}
// Pad left
public String padLeft(String text, int length, char padChar) {
if (text.length() >= length) {
return text;
}
StringBuilder sb = new StringBuilder();
int padLength = length - text.length();
for (int i = 0; i < padLength; i++) {
sb.append(padChar);
}
sb.append(text);
return sb.toString();
}
// Pad right
public String padRight(String text, int length, char padChar) {
if (text.length() >= length) {
return text;
}
StringBuilder sb = new StringBuilder(text);
int padLength = length - text.length();
for (int i = 0; i < padLength; i++) {
sb.append(padChar);
}
return sb.toString();
}
// Remove leading/trailing characters
public String strip(String text, char stripChar) {
int start = 0;
int end = text.length();
while (start < end && text.charAt(start) == stripChar) {
start++;
}
while (end > start && text.charAt(end - 1) == stripChar) {
end--;
}
return text.substring(start, end);
}
// Center text
public String center(String text, int width, char padChar) {
if (text.length() >= width) {
return text;
}
int totalPad = width - text.length();
int leftPad = totalPad / 2;
int rightPad = totalPad - leftPad;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < leftPad; i++) {
sb.append(padChar);
}
sb.append(text);
for (int i = 0; i < rightPad; i++) {
sb.append(padChar);
}
return sb.toString();
}
}
// 6. String Comparison
public class StringComparison {
// Compare strings (case-sensitive)
public boolean equals(String str1, String str2) {
return Objects.equals(str1, str2);
}
// Compare strings (case-insensitive)
public boolean equalsIgnoreCase(String str1, String str2) {
return str1 != null && str1.equalsIgnoreCase(str2);
}
// Compare strings with natural ordering
public int compare(String str1, String str2) {
return str1.compareTo(str2);
}
// Find common prefix
public String commonPrefix(String str1, String str2) {
int minLength = Math.min(str1.length(), str2.length());
int i = 0;
while (i < minLength && str1.charAt(i) == str2.charAt(i)) {
i++;
}
return str1.substring(0, i);
}
// Find common suffix
public String commonSuffix(String str1, String str2) {
int i = 0;
int len1 = str1.length();
int len2 = str2.length();
while (i < len1 && i < len2 &&
str1.charAt(len1 - 1 - i) == str2.charAt(len2 - 1 - i)) {
i++;
}
return str1.substring(len1 - i);
}
// Calculate Levenshtein distance
public int levenshteinDistance(String str1, String str2) {
int m = str1.length();
int n = str2.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 0; i <= m; i++) {
dp[i][0] = i;
}
for (int j = 0; j <= n; j++) {
dp[0][j] = j;
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = 1 + Math.min(
Math.min(dp[i - 1][j], dp[i][j - 1]),
dp[i - 1][j - 1]
);
}
}
}
return dp[m][n];
}
}
// Main demonstration
public class StringSplitJoinDemo {
public static void demonstrateStringSplitJoin() {
System.out.println("=== Android Java String Split and Join Examples ===\n");
StringSplitter splitter = new StringSplitter();
// 1. Basic split
System.out.println("--- 1. Basic Split ---");
String text1 = "apple,banana,orange,grape";
String[] fruits = splitter.splitByDelimiter(text1, ",");
System.out.println("Split '" + text1 + "':");
for (String fruit : fruits) {
System.out.println(" - " + fruit);
}
// 2. Split by multiple delimiters
System.out.println("\n--- 2. Split by Multiple Delimiters ---");
String text2 = "apple,banana;orange|grape";
String[] multiDelim = splitter.splitByMultipleDelimiters(text2, new String[]{",", ";", "|"});
System.out.println("Split by [,,;,|]:");
for (String item : multiDelim) {
System.out.println(" - " + item);
}
// 3. Split by regex
System.out.println("\n--- 3. Split by Regex ---");
String text3 = "apple123banana456orange";
String[] regexSplit = splitter.splitByRegex(text3, "\\d+");
System.out.println("Split by digits:");
for (String item : regexSplit) {
System.out.println(" - " + item);
}
// 4. Split into lines
System.out.println("\n--- 4. Split into Lines ---");
String text4 = "Line 1\\nLine 2\\nLine 3";
String[] lines = splitter.splitIntoLines(text4);
System.out.println("Lines:");
for (String line : lines) {
System.out.println(" - " + line);
}
// 5. Join with delimiter
System.out.println("\n--- 5. Join with Delimiter ---");
StringJoiner joiner = new StringJoiner();
String joined = joiner.joinWithDelimiter(fruits, " | ");
System.out.println("Joined with ' | ': " + joined);
// 6. Join with prefix and suffix
System.out.println("\n--- 6. Join with Prefix/Suffix ---");
String joinedWithBrackets = joiner.joinWithPrefixSuffix(fruits, ", ", "[", "]");
System.out.println("Joined with brackets: " + joinedWithBrackets);
// 7. Parse CSV
System.out.println("\n--- 7. Parse CSV ---");
AdvancedStringOperations advanced = new AdvancedStringOperations();
String csvLine = "John,Doe,30,New York";
String[] parsedCSV = advanced.parseCSVLine(csvLine);
System.out.println("Parsed CSV:");
System.out.println(" Name: " + parsedCSV[0] + " " + parsedCSV[1]);
System.out.println(" Age: " + parsedCSV[2]);
System.out.println(" City: " + parsedCSV[3]);
// 8. Parse key-value pairs
System.out.println("\n--- 8. Parse Key-Value Pairs ---");
String kvText = "name=John;age=30;city=NYC";
Map<String, String> kvPairs = advanced.parseKeyValuePairs(kvText, ";", "=");
System.out.println("Parsed key-values:");
for (Map.Entry<String, String> entry : kvPairs.entrySet()) {
System.out.println(" " + entry.getKey() + ": " + entry.getValue());
}
// 9. Word wrap
System.out.println("\n--- 9. Word Wrap ---");
String longText = "This is a very long text that needs to be wrapped into multiple lines";
String[] wrapped = advanced.wordWrap(longText, 20);
System.out.println("Wrapped text:");
for (String line : wrapped) {
System.out.println(" " + line);
}
// 10. String utilities
System.out.println("\n--- 10. String Utilities ---");
StringUtils utils = new StringUtils();
System.out.println("Capitalize: " + advanced.capitalize("hello"));
System.out.println("Capitalize words: " + advanced.capitalizeWords("hello world"));
System.out.println("Reverse: " + advanced.reverse("hello"));
System.out.println("Count 'll' in 'hello hello': " + advanced.countOccurrences("hello hello", "ll"));
System.out.println("Is blank ' ': " + utils.isBlank(" "));
System.out.println("Truncate: " + utils.truncate("Hello World", 5));
System.out.println("Pad left: " + utils.padLeft("123", 5, '0'));
// 11. String comparison
System.out.println("\n--- 11. String Comparison ---");
StringComparison comparison = new StringComparison();
System.out.println("Equals 'hello' and 'hello': " + comparison.equals("hello", "hello"));
System.out.println("Equals ignore case 'Hello' and 'hello': " + comparison.equalsIgnoreCase("Hello", "hello"));
System.out.println("Common prefix of 'hello' and 'help': " + comparison.commonPrefix("hello", "help"));
System.out.println("Levenshtein distance of 'kitten' and 'sitting': " + comparison.levenshteinDistance("kitten", "sitting"));
System.out.println("\n=== All String Split and Join Examples Completed ===");
}
}
💻 Remplacement de Chaînes java
🟢 simple
⭐⭐
Remplacer des sous-chaînes utilisant diverses méthodes incluant remplacement simple, basé sur regex et remplacement conditionnel
⏱️ 20 min
🏷️ java, android, string processing
Prerequisites:
Basic Java knowledge
// Android Java String Replacement Examples
// Java standard library string replacement methods
import java.util.*;
import java.util.regex.*;
// 1. Basic Replacement
public class BasicReplacement {
// Replace first occurrence
public String replaceFirst(String text, String target, String replacement) {
return text.replaceFirst(Pattern.quote(target), replacement);
}
// Replace all occurrences
public String replaceAll(String text, String target, String replacement) {
return text.replaceAll(Pattern.quote(target), replacement);
}
// Replace using char (single character)
public String replaceChar(String text, char oldChar, char newChar) {
return text.replace(oldChar, newChar);
}
// Replace using CharSequence
public String replaceSequence(String text, String target, String replacement) {
return text.replace(target, replacement);
}
// Replace with case-insensitive
public String replaceIgnoreCase(String text, String target, String replacement) {
Pattern p = Pattern.compile(target, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(text);
return m.replaceAll(replacement);
}
}
// 2. Conditional Replacement
public class ConditionalReplacement {
// Replace if condition met
public String replaceIf(String text, String target, String replacement, boolean condition) {
if (condition) {
return text.replace(target, replacement);
}
return text;
}
// Replace with map lookup
public String replaceWithMap(String text, Map<String, String> replacements) {
String result = text;
for (Map.Entry<String, String> entry : replacements.entrySet()) {
result = result.replace(entry.getKey(), entry.getValue());
}
return result;
}
// Replace with function
public String replaceWithFunction(String text, String pattern, java.util.function.Function<Matcher, String> func) {
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, func.apply(m));
}
m.appendTail(sb);
return sb.toString();
}
// Replace only whole words
public String replaceWholeWords(String text, String target, String replacement) {
String pattern = "\\b" + Pattern.quote(target) + "\\b";
return text.replaceAll(pattern, replacement);
}
}
// 3. Multiple Replacements
public class MultipleReplacements {
// Chain of replacements
public String chainReplace(String text, List<ReplacementRule> rules) {
String result = text;
for (ReplacementRule rule : rules) {
result = result.replaceAll(rule.pattern, rule.replacement);
}
return result;
}
// Replace multiple targets at once
public String replaceMultiple(String text, String[] targets, String replacement) {
String result = text;
for (String target : targets) {
result = result.replace(target, replacement);
}
return result;
}
// Parallel replacement
public Map<String, String> parallelReplace(Map<String, String> inputs, String target, String replacement) {
Map<String, String> results = new HashMap<>();
for (Map.Entry<String, String> entry : inputs.entrySet()) {
results.put(entry.getKey(), entry.getValue().replace(target, replacement));
}
return results;
}
public static class ReplacementRule {
public String pattern;
public String replacement;
public ReplacementRule(String pattern, String replacement) {
this.pattern = pattern;
this.replacement = replacement;
}
}
}
// 4. Advanced Replacement
public class AdvancedReplacement {
// Swap two substrings
public String swapSubstrings(String text, String first, String second) {
return text.replace(first, "\\0").replace(second, first).replace("\\0", second);
}
// Rotate replacements
public String rotateReplacements(String text, String[] values) {
String result = text;
int index = 0;
Pattern p = Pattern.compile("\\{\}");
Matcher m = p.matcher(result);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String replacement = values[index % values.length];
m.appendReplacement(sb, Matcher.quoteReplacement(replacement));
index++;
}
m.appendTail(sb);
return sb.toString();
}
// Template replacement
public String replaceTemplate(String template, Map<String, String> values) {
String result = template;
for (Map.Entry<String, String> entry : values.entrySet()) {
String placeholder = "\ + entry.getKey() + ";
result = result.replace(placeholder, entry.getValue());
}
return result;
}
// Number placeholders
public String replaceNumberedPlaceholders(String template, String[] values) {
String result = template;
for (int i = 0; i < values.length; i++) {
String placeholder = "%" + (i + 1);
result = result.replace(placeholder, values[i]);
}
return result;
}
}
// 5. Text Cleanup
public class TextCleanup {
// Remove accents
public String removeAccents(String text) {
String normalized = java.text.Normalizer.normalize(text, java.text.Normalizer.Form.NFD);
return normalized.replaceAll("\\p{M}", "");
}
// Normalize line endings
public String normalizeLineEndings(String text) {
return text.replaceAll("\\r\\n", "\\n").replaceAll("\\r", "\\n");
}
// Trim leading/trailing whitespace from each line
public String trimLines(String text) {
String[] lines = text.split("\\n");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < lines.length; i++) {
if (i > 0) {
sb.append("\\n");
}
sb.append(lines[i].trim());
}
return sb.toString();
}
// Remove empty lines
public String removeEmptyLines(String text) {
return text.replaceAll("^\\s*\\n|\\n\\s*$", "");
}
// Collapse multiple consecutive spaces
public String collapseSpaces(String text) {
return text.replaceAll(" +", " ");
}
// Remove control characters
public String removeControlCharacters(String text) {
return text.replaceAll("\\p{C}", "");
}
// Sanitize for filename
public String sanitizeFilename(String filename) {
return filename.replaceAll("[^a-zA-Z0-9._-]", "_");
}
// Convert to title case
public String toTitleCase(String text) {
String[] words = text.split("\\s+");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.length; i++) {
if (i > 0) {
sb.append(" ");
}
if (!words[i].isEmpty()) {
sb.append(Character.toUpperCase(words[i].charAt(0)));
if (words[i].length() > 1) {
sb.append(words[i].substring(1).toLowerCase());
}
}
}
return sb.toString();
}
}
// 6. Smart Replacement
public class SmartReplacement {
// Replace with incrementing counter
public String replaceWithCounter(String text, String pattern, int start) {
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
StringBuffer sb = new StringBuffer();
int[] counter = {start};
while (m.find()) {
m.appendReplacement(sb, String.valueOf(counter[0]++));
}
m.appendTail(sb);
return sb.toString();
}
// Replace with alternating values
public String replaceAlternating(String text, String pattern, String[] values) {
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
StringBuffer sb = new StringBuffer();
int[] index = {0};
while (m.find()) {
m.appendReplacement(sb, values[index[0] % values.length]);
index[0]++;
}
m.appendTail(sb);
return sb.toString();
}
// Conditional replacement based on context
public String replaceConditional(String text, String pattern, java.util.function.Function<Matcher, String> condition) {
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String replacement = condition.apply(m);
if (replacement != null) {
m.appendReplacement(sb, replacement);
}
}
m.appendTail(sb);
return sb.toString();
}
}
// Main demonstration
public class StringReplacementDemo {
public static void demonstrateStringReplacement() {
System.out.println("=== Android Java String Replacement Examples ===\n");
// 1. Basic replacement
System.out.println("--- 1. Basic Replacement ---");
BasicReplacement basic = new BasicReplacement();
String text1 = "Hello World, World is great";
System.out.println("Original: " + text1);
System.out.println("Replace first 'World': " + basic.replaceFirst(text1, "World", "Java"));
System.out.println("Replace all 'World': " + basic.replaceAll(text1, "World", "Java"));
System.out.println("Replace char 'o' with '0': " + basic.replaceChar(text1, 'o', '0'));
// 2. Case-insensitive replacement
String text2 = "Hello HELLO HeLLo hELLo";
System.out.println("\nOriginal: " + text2);
System.out.println("Replace 'hello' (case-insensitive): " + basic.replaceIgnoreCase(text2, "hello", "Java"));
// 3. Conditional replacement
System.out.println("\n--- 2. Conditional Replacement ---");
ConditionalReplacement conditional = new ConditionalReplacement();
String text3 = "The price is $100";
System.out.println("Original: " + text3);
System.out.println("Replace if true: " + conditional.replaceIf(text3, "$100", "$200", true));
System.out.println("Replace if false: " + conditional.replaceIf(text3, "$100", "$200", false));
Map<String, String> replacements = new HashMap<>();
replacements.put("apple", "fruit");
replacements.put("carrot", "vegetable");
String text4 = "I like apple and carrot";
System.out.println("Replace with map: " + conditional.replaceWithMap(text4, replacements));
// 4. Whole word replacement
String text5 = "The cat and catalog are different";
System.out.println("\nOriginal: " + text5);
System.out.println("Replace whole word 'cat': " + conditional.replaceWholeWords(text5, "cat", "dog"));
System.out.println("Replace all 'cat': " + text5.replace("cat", "dog"));
// 5. Multiple replacements
System.out.println("\n--- 3. Multiple Replacements ---");
MultipleReplacements multiple = new MultipleReplacements();
List<MultipleReplacements.ReplacementRule> rules = new ArrayList<>();
rules.add(new MultipleReplacements.ReplacementRule("&", "&"));
rules.add(new MultipleReplacements.ReplacementRule("<", "<"));
rules.add(new MultipleReplacements.ReplacementRule(">", ">"));
String html = "5 < 10 & 10 > 5";
System.out.println("HTML escape: " + multiple.chainReplace(html, rules));
// 6. Advanced replacement
System.out.println("\n--- 4. Advanced Replacement ---");
AdvancedReplacement advanced = new AdvancedReplacement();
String template1 = "Hello ${name}, welcome to ${place}";
Map<String, String> values1 = new HashMap<>();
values1.put("name", "John");
values1.put("place", "Tokyo");
System.out.println("Template replacement: " + advanced.replaceTemplate(template1, values1));
String template2 = "Dear %1, your order %2 is ready";
System.out.println("Numbered placeholders: " + advanced.replaceNumberedPlaceholders(template2, new String[]{"John", "#12345"}));
// 7. Text cleanup
System.out.println("\n--- 5. Text Cleanup ---");
TextCleanup cleanup = new TextCleanup();
String messyText = " Hello World \n\n Test \n";
System.out.println("Original: '" + messyText + "'");
System.out.println("Normalize: '" + cleanup.normalizeLineEndings(messyText) + "'");
System.out.println("Trim lines: '" + cleanup.trimLines(messyText) + "'");
System.out.println("Collapse spaces: '" + cleanup.collapseSpaces("Hello World Test") + "'");
System.out.println("Remove accents: " + cleanup.removeAccents("café résumé naïve"));
System.out.println("Title case: " + cleanup.toTitleCase("hello world from java"));
// 8. Smart replacement
System.out.println("\n--- 6. Smart Replacement ---");
SmartReplacement smart = new SmartReplacement();
String counterText = "Item _, Item _, Item _";
System.out.println("Replace with counter: " + smart.replaceWithCounter(counterText, "_", 1));
String alternatingText = "Color _, Color _, Color _";
System.out.println("Alternating colors: " + smart.replaceAlternating(alternatingText, "_", new String[]{"red", "blue", "green"}));
// 9. Context-aware replacement
String contextText = "price: 100, cost: 200, value: 300";
String result = smart.replaceConditional(contextText, "\\d+", matcher -> {
int num = Integer.parseInt(matcher.group());
return String.valueOf(num * 2);
});
System.out.println("Double numbers: " + result);
System.out.println("\n=== All String Replacement Examples Completed ===");
}
}
💻 Expressions Régulières java
🟡 intermediate
⭐⭐⭐
Correspondance de modèles, validation, recherche et remplacement utilisant des expressions régulières
⏱️ 30 min
🏷️ java, android, string processing, regex
Prerequisites:
Intermediate Java, Understanding of regex
// Android Java Regular Expression Examples
// Java standard library regex support
import java.util.*;
import java.util.regex.*;
// 1. Basic Pattern Matching
public class RegexMatcher {
// Check if pattern matches entire string
public boolean matchesFullString(String text, String pattern) {
return Pattern.matches(pattern, text);
}
// Check if pattern contains in string
public boolean containsPattern(String text, String pattern) {
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
return m.find();
}
// Find first match
public String findFirstMatch(String text, String pattern) {
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
if (m.find()) {
return m.group();
}
return null;
}
// Find all matches
public List<String> findAllMatches(String text, String pattern) {
List<String> matches = new ArrayList<>();
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
while (m.find()) {
matches.add(m.group());
}
return matches;
}
// Find matches with groups
public List<List<String>> findGroupMatches(String text, String pattern) {
List<List<String>> results = new ArrayList<>();
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
while (m.find()) {
List<String> groups = new ArrayList<>();
for (int i = 0; i <= m.groupCount(); i++) {
groups.add(m.group(i));
}
results.add(groups);
}
return results;
}
}
// 2. Common Validation Patterns
public class StringValidator {
// Validate email
public boolean isValidEmail(String email) {
String emailPattern = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$";
return Pattern.matches(emailPattern, email);
}
// Validate phone number
public boolean isValidPhoneNumber(String phone) {
String phonePattern = "^\\+?[1-9]\\d{1,14}$";
return Pattern.matches(phonePattern, phone);
}
// Validate URL
public boolean isValidURL(String url) {
String urlPattern = "^https?://[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}(/[^\\s]*)?$";
return Pattern.matches(urlPattern, url);
}
// Validate IPv4 address
public boolean isValidIPv4(String ip) {
String ipPattern = "^((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 Pattern.matches(ipPattern, ip);
}
// Validate credit card (basic format)
public boolean isValidCreditCard(String card) {
String cardPattern = "^\\d{13,19}$";
return Pattern.matches(cardPattern, card.replaceAll("\\s", ""));
}
// Validate hexadecimal color
public boolean isValidHexColor(String color) {
String colorPattern = "^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$";
return Pattern.matches(colorPattern, color);
}
// Validate strong password
public boolean isStrongPassword(String password) {
// At least 8 chars, 1 uppercase, 1 lowercase, 1 digit, 1 special
String passwordPattern = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$";
return Pattern.matches(passwordPattern, password);
}
// Validate date format (YYYY-MM-DD)
public boolean isValidDate(String date) {
String datePattern = "^\\d{4}-\\d{2}-\\d{2}$";
return Pattern.matches(datePattern, date);
}
// Validate username (alphanumeric, underscore, 3-20 chars)
public boolean isValidUsername(String username) {
String usernamePattern = "^[a-zA-Z0-9_]{3,20}$";
return Pattern.matches(usernamePattern, username);
}
// Validate postal code (US format)
public boolean isValidPostalCode(String code) {
String postalPattern = "^\\d{5}(-\\d{4})?$";
return Pattern.matches(postalPattern, code);
}
}
// 3. Search and Extract
public class RegexSearcher {
// Extract all email addresses
public List<String> extractEmails(String text) {
String emailPattern = "[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}";
return new RegexMatcher().findAllMatches(text, emailPattern);
}
// Extract all URLs
public List<String> extractURLs(String text) {
String urlPattern = "https?://[^\\s]+";
return new RegexMatcher().findAllMatches(text, urlPattern);
}
// Extract all hashtags
public List<String> extractHashtags(String text) {
String hashtagPattern = "#\\w+";
return new RegexMatcher().findAllMatches(text, hashtagPattern);
}
// Extract all mentions
public List<String> extractMentions(String text) {
String mentionPattern = "@\\w+";
return new RegexMatcher().findAllMatches(text, mentionPattern);
}
// Extract numbers
public List<Double> extractNumbers(String text) {
String numberPattern = "-?\\d+\\.\\d+|-?\\d+";
List<String> matches = new RegexMatcher().findAllMatches(text, numberPattern);
List<Double> numbers = new ArrayList<>();
for (String match : matches) {
try {
numbers.add(Double.parseDouble(match));
} catch (NumberFormatException e) {
// Skip invalid numbers
}
}
return numbers;
}
// Extract quoted text
public List<String> extractQuotedText(String text) {
String quotePattern = "\"([^"]*)\"";
List<List<String>> groups = new RegexMatcher().findGroupMatches(text, quotePattern);
List<String> quotes = new ArrayList<>();
for (List<String> group : groups) {
if (group.size() > 1) {
quotes.add(group.get(1));
}
}
return quotes;
}
}
// 4. Text Processing with Regex
public class RegexTextProcessor {
// Remove extra whitespace
public String normalizeWhitespace(String text) {
return text.replaceAll("\\s+", " ").trim();
}
// Remove all special characters
public String removeSpecialCharacters(String text) {
return text.replaceAll("[^a-zA-Z0-9\\s]", "");
}
// Remove all digits
public String removeDigits(String text) {
return text.replaceAll("\\d", "");
}
// Remove all letters
public String removeLetters(String text) {
return text.replaceAll("[a-zA-Z]", "");
}
// Replace multiple spaces with single space
public String collapseSpaces(String text) {
return text.replaceAll(" +", " ");
}
// Remove HTML tags
public String stripHTMLTags(String text) {
return text.replaceAll("<[^>]*>", "");
}
// Mask email addresses
public String maskEmails(String text) {
return text.replaceAll(
"([A-Za-z0-9+_.-]+)@([A-Za-z0-9.-]+\\.[A-Za-z]{2,})",
"***@$2"
);
}
// Mask phone numbers
public String maskPhoneNumbers(String text) {
return text.replaceAll(
"\\+?[1-9]\\d{1,14}",
"***"
);
}
// Sanitize filename
public String sanitizeFilename(String filename) {
return filename.replaceAll("[^a-zA-Z0-9._-]", "_");
}
}
// 5. Regex Replacement with Callback
public class RegexReplacer {
// Replace with count
public String replaceFirst(String text, String pattern, String replacement) {
return text.replaceFirst(pattern, replacement);
}
// Replace all
public String replaceAll(String text, String pattern, String replacement) {
return text.replaceAll(pattern, replacement);
}
// Replace with function
public String replaceWithCallback(String text, String pattern, java.util.function.Function<Matcher, String> callback) {
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, callback.apply(m));
}
m.appendTail(sb);
return sb.toString();
}
// Capitalize words after period
public String capitalizeAfterPeriod(String text) {
return replaceWithCallback(text, "\\.\\s*([a-z])", matcher -> {
return ". " + matcher.group(1).toUpperCase();
});
}
// Wrap URLs in links
public String wrapURLsInLinks(String text) {
String urlPattern = "(https?://[^\\s]+)";
return replaceWithCallback(text, urlPattern, matcher -> {
return "<a href=\"" + matcher.group(1) + "\">" + matcher.group(1) + "</a>";
});
}
}
// 6. Pattern Compilation and Reuse
public class PatternCache {
private Map<String, Pattern> cache = new HashMap<>();
public Pattern getPattern(String regex) {
if (!cache.containsKey(regex)) {
cache.put(regex, Pattern.compile(regex));
}
return cache.get(regex);
}
public Matcher getMatcher(String regex, String text) {
return getPattern(regex).matcher(text);
}
public boolean matches(String regex, String text) {
return getPattern(regex).matcher(text).matches();
}
public boolean contains(String regex, String text) {
return getPattern(regex).matcher(text).find();
}
}
// Main demonstration
public class RegexDemo {
public static void demonstrateRegex() {
System.out.println("=== Android Java Regular Expression Examples ===\n");
// 1. Basic pattern matching
System.out.println("--- 1. Basic Pattern Matching ---");
RegexMatcher matcher = new RegexMatcher();
String text = "The price is $123.45";
System.out.println("Contains digits: " + matcher.containsPattern(text, "\\d+"));
System.out.println("First digit match: " + matcher.findFirstMatch(text, "\\d+"));
System.out.println("All matches for \\d+: " + matcher.findAllMatches(text, "\\d+"));
// 2. Validation
System.out.println("\n--- 2. String Validation ---");
StringValidator validator = new StringValidator();
System.out.println("Valid email '[email protected]': " + validator.isValidEmail("[email protected]"));
System.out.println("Valid phone '+1234567890': " + validator.isValidPhoneNumber("+1234567890"));
System.out.println("Valid URL 'https://example.com': " + validator.isValidURL("https://example.com"));
System.out.println("Valid IPv4 '192.168.1.1': " + validator.isValidIPv4("192.168.1.1"));
System.out.println("Valid hex color '#FF5733': " + validator.isValidHexColor("#FF5733"));
System.out.println("Strong password 'Pass123!': " + validator.isStrongPassword("Pass123!"));
System.out.println("Valid username 'user_123': " + validator.isValidUsername("user_123"));
// 3. Extraction
System.out.println("\n--- 3. Extract Information ---");
RegexSearcher searcher = new RegexSearcher();
String sampleText = "Contact us at [email protected] or [email protected]. " +
"Visit https://example.com for more info. " +
"Follow @user on Twitter! #example";
System.out.println("Emails: " + searcher.extractEmails(sampleText));
System.out.println("URLs: " + searcher.extractURLs(sampleText));
System.out.println("Hashtags: " + searcher.extractHashtags(sampleText));
System.out.println("Mentions: " + searcher.extractMentions(sampleText));
String numbersText = "The values are 123.45, 67, and -89.5";
System.out.println("Numbers: " + searcher.extractNumbers(numbersText));
String quotedText = "He said \"Hello\" and she replied \"Hi\"";
System.out.println("Quotes: " + searcher.extractQuotedText(quotedText));
// 4. Text processing
System.out.println("\n--- 4. Text Processing ---");
RegexTextProcessor processor = new RegexTextProcessor();
String messyText = "This has extra spaces ";
System.out.println("Normalize: '" + processor.normalizeWhitespace(messyText) + "'");
String specialChars = "Hello@#$%World123!";
System.out.println("Remove special: '" + processor.removeSpecialCharacters(specialChars) + "'");
System.out.println("Remove digits: '" + processor.removeDigits(specialChars) + "'");
String html = "<p>This is <b>bold</b> text</p>";
System.out.println("Strip HTML: '" + processor.stripHTMLTags(html) + "'");
String emailText = "Contact [email protected] for info";
System.out.println("Mask emails: '" + processor.maskEmails(emailText) + "'");
// 5. Replacement
System.out.println("\n--- 5. Regex Replacement ---");
RegexReplacer replacer = new RegexReplacer();
String replaceText = "The price is $100 and $200";
System.out.println("Replace $ with €: " + replacer.replaceAll(replaceText, "\\$", "€"));
String periodText = "hello. world. test. example";
System.out.println("Capitalize after period: " + replacer.capitalizeAfterPeriod(periodText));
String urlText = "Visit https://example.com and http://test.com";
System.out.println("Wrap URLs: " + replacer.wrapURLsInLinks(urlText));
// 6. Group matching
System.out.println("\n--- 6. Group Matching ---");
String dateText = "Date: 2024-12-28";
List<List<String>> dateGroups = matcher.findGroupMatches(dateText, "(\\d{4})-(\\d{2})-(\\d{2})");
System.out.println("Date groups: " + dateGroups);
String nameText = "John Doe and Jane Smith";
List<List<String>> nameGroups = matcher.findGroupMatches(nameText, "([A-Z][a-z]+) ([A-Z][a-z]+)");
System.out.println("Name groups: " + nameGroups);
System.out.println("\n=== All Regular Expression Examples Completed ===");
}
}