String Processing
Regular Expression Patterns
Real applications need to validate emails, extract phone numbers, parse URLs, and clean text. Reusable regex patterns help solve common validation and extraction tasks while keeping the matching logic explicit.
Email Validation
Email.java
Replay: real traced execution (multi-file project)
// Email validation patterns
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Email {
public static void main(String[] args) {
// Basic email pattern
String basicEmail = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
String[] emails = {
"user@example.com",
"first.last@domain.co.uk",
"user+tag@example.org",
"invalid@",
"@invalid.com",
"no-at-sign.com",
"user@domain",
"user@domain.c"
};
System.out.println("Basic email validation:");
Pattern pattern = Pattern.compile(basicEmail);
for (String email : emails) {
boolean valid = pattern.matcher(email).matches();
System.out.println(" " + email + ": " + valid);
}
// Extract email parts
String emailPattern = "^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\\.([a-zA-Z]{2,})$";
Pattern extractPattern = Pattern.compile(emailPattern);
System.out.println("\nExtract email parts:");
String testEmail = "john.doe@example.com";
Matcher matcher = extractPattern.matcher(testEmail);
if (matcher.matches()) {
System.out.println(" Email: " + testEmail);
System.out.println(" Username: " + matcher.group(1));
System.out.println(" Domain: " + matcher.group(2));
System.out.println(" TLD: " + matcher.group(3));
}
// Find all emails in text
String text = """
Contact us at support@example.com or sales@company.org.
For urgent matters, email admin@service.net immediately.
""";
Pattern findPattern = Pattern.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}");
Matcher findMatcher = findPattern.matcher(text);
System.out.println("\nEmails found in text:");
while (findMatcher.find()) {
System.out.println(" " + findMatcher.group());
}
// More strict pattern (requires valid TLD length)
String strictEmail = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$";
Pattern strictPattern = Pattern.compile(strictEmail);
System.out.println("\nStrict validation:");
String[] testEmails = {
"user@domain.com",
"user@domain.co",
"user@domain.technology" // 10 chars TLD
};
for (String email : testEmails) {
boolean valid = strictPattern.matcher(email).matches();
System.out.println(" " + email + ": " + valid);
}
}
}
// Email validation patterns
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Email {
public static void main(String[] args) {
// Basic email pattern
String basicEmail = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
String[] emails = {
"user@example.com",
"first.last@domain.co.uk",
"user+tag@example.org",
"invalid@",
"@invalid.com",
"no-at-sign.com",
"user@domain",
"user@domain.c"
};
System.out.println("Basic email validation:");
Pattern pattern = Pattern.compile(basicEmail);
for (String email : emails) {
boolean valid = pattern.matcher(email).matches();
System.out.println(" " + email + ": " + valid);
}
// Extract email parts
String emailPattern = "^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\\.([a-zA-Z]{2,})$";
Pattern extractPattern = Pattern.compile(emailPattern);
System.out.println("\nExtract email parts:");
String testEmail = "bad-address";
Matcher matcher = extractPattern.matcher(testEmail);
if (matcher.matches()) {
System.out.println(" Email: " + testEmail);
System.out.println(" Username: " + matcher.group(1));
System.out.println(" Domain: " + matcher.group(2));
System.out.println(" TLD: " + matcher.group(3));
}
// Find all emails in text
String text = """
Contact us at support@example.com or sales@company.org.
For urgent matters, email admin@service.net immediately.
""";
Pattern findPattern = Pattern.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}");
Matcher findMatcher = findPattern.matcher(text);
System.out.println("\nEmails found in text:");
while (findMatcher.find()) {
System.out.println(" " + findMatcher.group());
}
// More strict pattern (requires valid TLD length)
String strictEmail = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$";
Pattern strictPattern = Pattern.compile(strictEmail);
System.out.println("\nStrict validation:");
String[] testEmails = {
"user@domain.com",
"user@domain.co",
"user@domain.technology" // 10 chars TLD
};
for (String email : testEmails) {
boolean valid = strictPattern.matcher(email).matches();
System.out.println(" " + email + ": " + valid);
}
}
}
basicEmail ← ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
8public static void main(String[] args) {9 // Basic email pattern10 String basicEmail→ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";11 12 String[] emails = {13 "user@example.com",14 "first.last@domain.co.uk",15 "user+tag@example.org",16 "invalid@",17 "@invalid.com",18 "no-at-sign.com",19 "user@domain",20 "user@domain.c"21 };2223 System.out.println("Basic email validation:");24 Pattern pattern→ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ = Pattern.compile(basicEmail^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$);25 for (String email : emails) {outputBasic email validation:valid ← true
pass 1 of 824Pattern pattern = Pattern.compile(basicEmail);25for (String emailuser@example.com : emails) {26 boolean valid→ true = pattern.matcher(emailuser@example.com).matches();27 System.out.println(" " + emailuser@example.com + ": " + validtrue);28}output user@example.com: trueAll 8 passes — pass 1 is the card above pass emailvalid1 user@example.com true 2 first.last@domain.co.uk true 3 user+tag@example.org true 4 invalid@ false 5 @invalid.com false 6 no-at-sign.com false 7 user@domain false 8 user@domain.c false emailPattern ← ^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,})$
30// Extract email parts31String emailPattern→ ^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,})$ = "^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\\.([a-zA-Z]{2,})$";32Pattern extractPattern→ ^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,})$ = Pattern.compile(emailPattern^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,})$);3334System.out.println("\nExtract email parts:");35String testEmail→ john.doe@example.com = "john.doe@example.com"; //@testEmail="john.doe@example.com", "bad-address"36Matcher matcher→ java.util.regex.Matcher[pattern=^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,})$ region=0,20 lastmatch=] = extractPattern.matcher(testEmailjohn.doe@example.com);output Extract email parts:if (matcher.matches())
38if (matcher.matches()) {39 System.out.println(" Email: " + testEmailjohn.doe@example.com);40 System.out.println(" Username: " + matcher.group(1));41 System.out.println(" Domain: " + matcher.group(2));42 System.out.println(" TLD: " + matcher.group(3));43}output Email: john.doe@example.com Username: john.doe Domain: example TLD: comtext ← Contact us at support@example.com or sales@company.org. For urgent matters, email admin@service.net immediately.
45// Find all emails in text46String text→ Contact us at support@example.com or sales@company.org. For urgent matters, email admin@service.net immediately. = """47 Contact us at support@example.com or sales@company.org.48 For urgent matters, email admin@service.net immediately.49 """;5051Pattern findPattern→ [a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,} = Pattern.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}");52Matcher findMatcher→ java.util.regex.Matcher[pattern=[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,} region=0,113 lastmatch=] = findPattern.matcher(textContact us at support@example.com or sales@company.org. For urgent matters, email admin@service.net immediately. );5354System.out.println("\nEmails found in text:");55while (findMatcher.find()) {output Emails found in text:while (findMatcher.find())
pass 1 of 354System.out.println("\nEmails found in text:");55while (findMatcher.find()) {56 System.out.println(" " + findMatcher.group());57}output support@example.comstrictEmail ← ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$
59// More strict pattern (requires valid TLD length)60String strictEmail→ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$ = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$";61Pattern strictPattern→ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$ = Pattern.compile(strictEmail^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$);6263System.out.println("\nStrict validation:");64String[] testEmails = {65 "user@domain.com",66 "user@domain.co",67 "user@domain.technology" // 10 chars TLD68};output Strict validation:valid ← true
pass 1 of 370for (String emailuser@domain.com : testEmails) {71 boolean valid→ true = strictPattern.matcher(emailuser@domain.com).matches();72 System.out.println(" " + emailuser@domain.com + ": " + validtrue);73}output user@domain.com: trueAll 3 passes — pass 1 is the card above pass emailvalid1 user@domain.com true 2 user@domain.co true 3 user@domain.technology false
basicEmail ← ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
8public static void main(String[] args) {9 // Basic email pattern10 String basicEmail→ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";11 12 String[] emails = {13 "user@example.com",14 "first.last@domain.co.uk",15 "user+tag@example.org",16 "invalid@",17 "@invalid.com",18 "no-at-sign.com",19 "user@domain",20 "user@domain.c"21 };2223 System.out.println("Basic email validation:");24 Pattern pattern→ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ = Pattern.compile(basicEmail^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$);25 for (String email : emails) {outputBasic email validation:valid ← true
pass 1 of 824Pattern pattern = Pattern.compile(basicEmail);25for (String emailuser@example.com : emails) {26 boolean valid→ true = pattern.matcher(emailuser@example.com).matches();27 System.out.println(" " + emailuser@example.com + ": " + validtrue);28}output user@example.com: trueAll 8 passes — pass 1 is the card above pass emailvalid1 user@example.com true 2 first.last@domain.co.uk true 3 user+tag@example.org true 4 invalid@ false 5 @invalid.com false 6 no-at-sign.com false 7 user@domain false 8 user@domain.c false emailPattern ← ^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,})$
30// Extract email parts31String emailPattern→ ^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,})$ = "^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\\.([a-zA-Z]{2,})$";32Pattern extractPattern→ ^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,})$ = Pattern.compile(emailPattern^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,})$);3334System.out.println("\nExtract email parts:");35String testEmail→ bad-address = "bad-address";36Matcher matcher→ java.util.regex.Matcher[pattern=^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,})$ region=0,11 lastmatch=] = extractPattern.matcher(testEmailbad-address);3738if (matcher.matches()) {39 System.out.println(" Email: " + testEmail);40 System.out.println(" Username: " + matcher.group(1));41 System.out.println(" Domain: " + matcher.group(2));42 System.out.println(" TLD: " + matcher.group(3));43}4445// Find all emails in text46String text→ Contact us at support@example.com or sales@company.org. For urgent matters, email admin@service.net immediately. = """47 Contact us at support@example.com or sales@company.org.48 For urgent matters, email admin@service.net immediately.49 """;5051Pattern findPattern→ [a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,} = Pattern.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}");52Matcher findMatcher→ java.util.regex.Matcher[pattern=[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,} region=0,113 lastmatch=] = findPattern.matcher(textContact us at support@example.com or sales@company.org. For urgent matters, email admin@service.net immediately. );5354System.out.println("\nEmails found in text:");55while (findMatcher.find()) {output Extract email parts: Emails found in text:while (findMatcher.find())
pass 1 of 354System.out.println("\nEmails found in text:");55while (findMatcher.find()) {56 System.out.println(" " + findMatcher.group());57}output support@example.comstrictEmail ← ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$
59// More strict pattern (requires valid TLD length)60String strictEmail→ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$ = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$";61Pattern strictPattern→ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$ = Pattern.compile(strictEmail^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$);6263System.out.println("\nStrict validation:");64String[] testEmails = {65 "user@domain.com",66 "user@domain.co",67 "user@domain.technology" // 10 chars TLD68};output Strict validation:valid ← true
pass 1 of 370for (String emailuser@domain.com : testEmails) {71 boolean valid→ true = strictPattern.matcher(emailuser@domain.com).matches();72 System.out.println(" " + emailuser@domain.com + ": " + validtrue);73}output user@domain.com: trueAll 3 passes — pass 1 is the card above pass emailvalid1 user@domain.com true 2 user@domain.co true 3 user@domain.technology false
email_pattern
An email pattern matches a local part, an at sign, a domain, and a top-level domain. Production email validation can be stricter than this simplified form.
Phone Number Validation
Phone.java
Replay: real traced execution (multi-file project)
// Phone number patterns
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Phone {
public static void main(String[] args) {
// US phone formats
String[] patterns = {
"\\(\\d{3}\\)\\s\\d{3}-\\d{4}", // (123) 456-7890
"\\d{3}-\\d{3}-\\d{4}", // 123-456-7890
"\\d{10}" // 1234567890
};
String[] phones = {
"(555) 123-4567",
"555-123-4567",
"5551234567",
"(555)123-4567", // no space
"555.123.4567",
"invalid"
};
System.out.println("Phone validation:");
for (int i = 0; i < patterns.length; i++) {
System.out.println("\nPattern " + (i+1) + ":");
Pattern p = Pattern.compile(patterns[i]);
for (String phone : phones) {
boolean valid = p.matcher(phone).matches();
System.out.println(" " + phone + ": " + valid);
}
}
// Combined pattern (any format)
String anyFormat = "^(\\(\\d{3}\\)\\s?|\\d{3}-)?\\d{3}-?\\d{4}$";
Pattern anyPattern = Pattern.compile(anyFormat);
System.out.println("\nCombined pattern:");
for (String phone : phones) {
boolean valid = anyPattern.matcher(phone).matches();
System.out.println(" " + phone + ": " + valid);
}
// Extract phone parts
String extractPattern = "\\((\\d{3})\\)\\s(\\d{3})-(\\d{4})";
Pattern extract = Pattern.compile(extractPattern);
String testPhone = "(555) 123-4567";
Matcher matcher = extract.matcher(testPhone);
if (matcher.matches()) {
System.out.println("\nExtracted parts from " + testPhone + ":");
System.out.println(" Area code: " + matcher.group(1));
System.out.println(" Exchange: " + matcher.group(2));
System.out.println(" Number: " + matcher.group(3));
}
// Find all phones in text
String text = """
Call us at (555) 123-4567 or 555-987-6543.
Emergency: (999) 911-0000
""";
Pattern findPattern = Pattern.compile("\\(?\\d{3}\\)?[-\\s]?\\d{3}-\\d{4}");
Matcher findMatcher = findPattern.matcher(text);
System.out.println("\nPhones found in text:");
while (findMatcher.find()) {
System.out.println(" " + findMatcher.group());
}
// International format (basic)
String intlPattern = "^\\+?\\d{1,3}[-\\s]?\\(?\\d{1,4}\\)?[-\\s]?\\d{1,4}[-\\s]?\\d{1,9}$";
Pattern intlP = Pattern.compile(intlPattern);
String[] intlPhones = {
"+1 (555) 123-4567",
"+44 20 7123 4567",
"+81 3-1234-5678"
};
System.out.println("\nInternational phones:");
for (String phone : intlPhones) {
boolean valid = intlP.matcher(phone).matches();
System.out.println(" " + phone + ": " + valid);
}
}
}
// Phone number patterns
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Phone {
public static void main(String[] args) {
// US phone formats
String[] patterns = {
"\\(\\d{3}\\)\\s\\d{3}-\\d{4}", // (123) 456-7890
"\\d{3}-\\d{3}-\\d{4}", // 123-456-7890
"\\d{10}" // 1234567890
};
String[] phones = {
"(555) 123-4567",
"555-123-4567",
"5551234567",
"(555)123-4567", // no space
"555.123.4567",
"invalid"
};
System.out.println("Phone validation:");
for (int i = 0; i < patterns.length; i++) {
System.out.println("\nPattern " + (i+1) + ":");
Pattern p = Pattern.compile(patterns[i]);
for (String phone : phones) {
boolean valid = p.matcher(phone).matches();
System.out.println(" " + phone + ": " + valid);
}
}
// Combined pattern (any format)
String anyFormat = "^(\\(\\d{3}\\)\\s?|\\d{3}-)?\\d{3}-?\\d{4}$";
Pattern anyPattern = Pattern.compile(anyFormat);
System.out.println("\nCombined pattern:");
for (String phone : phones) {
boolean valid = anyPattern.matcher(phone).matches();
System.out.println(" " + phone + ": " + valid);
}
// Extract phone parts
String extractPattern = "\\((\\d{3})\\)\\s(\\d{3})-(\\d{4})";
Pattern extract = Pattern.compile(extractPattern);
String testPhone = "555-123-4567";
Matcher matcher = extract.matcher(testPhone);
if (matcher.matches()) {
System.out.println("\nExtracted parts from " + testPhone + ":");
System.out.println(" Area code: " + matcher.group(1));
System.out.println(" Exchange: " + matcher.group(2));
System.out.println(" Number: " + matcher.group(3));
}
// Find all phones in text
String text = """
Call us at (555) 123-4567 or 555-987-6543.
Emergency: (999) 911-0000
""";
Pattern findPattern = Pattern.compile("\\(?\\d{3}\\)?[-\\s]?\\d{3}-\\d{4}");
Matcher findMatcher = findPattern.matcher(text);
System.out.println("\nPhones found in text:");
while (findMatcher.find()) {
System.out.println(" " + findMatcher.group());
}
// International format (basic)
String intlPattern = "^\\+?\\d{1,3}[-\\s]?\\(?\\d{1,4}\\)?[-\\s]?\\d{1,4}[-\\s]?\\d{1,9}$";
Pattern intlP = Pattern.compile(intlPattern);
String[] intlPhones = {
"+1 (555) 123-4567",
"+44 20 7123 4567",
"+81 3-1234-5678"
};
System.out.println("\nInternational phones:");
for (String phone : intlPhones) {
boolean valid = intlP.matcher(phone).matches();
System.out.println(" " + phone + ": " + valid);
}
}
}
public static void main(String[] args)
8public static void main(String[] args) {9 // US phone formats10 String[] patterns = {11 "\\(\\d{3}\\)\\s\\d{3}-\\d{4}", // (123) 456-789012 "\\d{3}-\\d{3}-\\d{4}", // 123-456-789013 "\\d{10}" // 123456789014 };1516 String[] phones = {17 "(555) 123-4567",18 "555-123-4567",19 "5551234567",20 "(555)123-4567", // no space21 "555.123.4567",22 "invalid"23 };2425 System.out.println("Phone validation:");26 for (int i = 0; i < patterns.length; i++) {outputPhone validation:p ← \(\d{3}\)\s\d{3}-\d{4}
pass 1 of 325System.out.println("Phone validation:");26for (int i0 = 0; i < patterns.length3; i++) {27 System.out.println("\nPattern " + (i0+1) + ":");28 Pattern p→ \(\d{3}\)\s\d{3}-\d{4} = Pattern.compile(patterns[i]\(\d{3}\)\s\d{3}-\d{4});29 for (String phone : phones) {output Pattern 1:All 3 passes — pass 1 is the card above pass ipatterns[i]p1 0 \(\d{3}\)\s\d{3}-\d{4} \(\d{3}\)\s\d{3}-\d{4} 2 1 \d{3}-\d{3}-\d{4} \d{3}-\d{3}-\d{4} 3 2 \d{10} \d{10} valid ← true
pass 1 of 1828Pattern p = Pattern.compile(patterns[i]);29for (String phone(555) 123-4567 : phones) {30 boolean valid→ true = p.matcher(phone(555) 123-4567).matches();31 System.out.println(" " + phone(555) 123-4567 + ": " + validtrue);32}output (555) 123-4567: true18 passes — pass 1 is the card above pass phonevalid1 (555) 123-4567 true 2 555-123-4567 false 3 5551234567 false 4 (555)123-4567 false 5 555.123.4567 false 6 invalid false 7 (555) 123-4567 false 8 555-123-4567 true 9 5551234567 false ⋯ 7 more passes ⋯ 17 555.123.4567 false 18 invalid false anyFormat ← ^(\(\d{3}\)\s?|\d{3}-)?\d{3}-?\d{4}$, anyPattern ← ^(\(\d{3}\)\s?|\d{3}-)?\d{3}-?\d{4}$
35// Combined pattern (any format)36String anyFormat→ ^(\(\d{3}\)\s?|\d{3}-)?\d{3}-?\d{4}$ = "^(\\(\\d{3}\\)\\s?|\\d{3}-)?\\d{3}-?\\d{4}$";37Pattern anyPattern→ ^(\(\d{3}\)\s?|\d{3}-)?\d{3}-?\d{4}$ = Pattern.compile(anyFormat^(\(\d{3}\)\s?|\d{3}-)?\d{3}-?\d{4}$);3839System.out.println("\nCombined pattern:");40for (String phone : phones) {output Combined pattern:valid ← true
pass 1 of 639System.out.println("\nCombined pattern:");40for (String phone(555) 123-4567 : phones) {41 boolean valid→ true = anyPattern.matcher(phone(555) 123-4567).matches();42 System.out.println(" " + phone(555) 123-4567 + ": " + validtrue);43}output (555) 123-4567: trueAll 6 passes — pass 1 is the card above pass phonevalid1 (555) 123-4567 true 2 555-123-4567 true 3 5551234567 false 4 (555)123-4567 true 5 555.123.4567 false 6 invalid false extractPattern ← \((\d{3})\)\s(\d{3})-(\d{4}), extract ← \((\d{3})\)\s(\d{3})-(\d{4})
45// Extract phone parts46String extractPattern→ \((\d{3})\)\s(\d{3})-(\d{4}) = "\\((\\d{3})\\)\\s(\\d{3})-(\\d{4})";47Pattern extract→ \((\d{3})\)\s(\d{3})-(\d{4}) = Pattern.compile(extractPattern\((\d{3})\)\s(\d{3})-(\d{4}));4849String testPhone→ (555) 123-4567 = "(555) 123-4567"; //@testPhone="(555) 123-4567", "555-123-4567"50Matcher matcher→ java.util.regex.Matcher[pattern=\((\d{3})\)\s(\d{3})-(\d{4}) region=0,14 lastmatch=] = extract.matcher(testPhone(555) 123-4567);if (matcher.matches())
52if (matcher.matches()) {53 System.out.println("\nExtracted parts from " + testPhone(555) 123-4567 + ":");54 System.out.println(" Area code: " + matcher.group(1));55 System.out.println(" Exchange: " + matcher.group(2));56 System.out.println(" Number: " + matcher.group(3));57}output Extracted parts from (555) 123-4567: Area code: 555 Exchange: 123 Number: 4567text ← Call us at (555) 123-4567 or 555-987-6543. Emergency: (999) 911-0000
59// Find all phones in text60String text→ Call us at (555) 123-4567 or 555-987-6543. Emergency: (999) 911-0000 = """61 Call us at (555) 123-4567 or 555-987-6543.62 Emergency: (999) 911-000063 """;6465Pattern findPattern→ \(?\d{3}\)?[-\s]?\d{3}-\d{4} = Pattern.compile("\\(?\\d{3}\\)?[-\\s]?\\d{3}-\\d{4}");66Matcher findMatcher→ java.util.regex.Matcher[pattern=\(?\d{3}\)?[-\s]?\d{3}-\d{4} region=0,69 lastmatch=] = findPattern.matcher(textCall us at (555) 123-4567 or 555-987-6543. Emergency: (999) 911-0000 );6768System.out.println("\nPhones found in text:");69while (findMatcher.find()) {output Phones found in text:while (findMatcher.find())
pass 1 of 368System.out.println("\nPhones found in text:");69while (findMatcher.find()) {70 System.out.println(" " + findMatcher.group());71}output (555) 123-4567intlPattern ← ^\+?\d{1,3}[-\s]?\(?\d{1,4}\)?[-\s]?\d{1,4}[-\s]?\d{1,9}$
73// International format (basic)74String intlPattern→ ^\+?\d{1,3}[-\s]?\(?\d{1,4}\)?[-\s]?\d{1,4}[-\s]?\d{1,9}$ = "^\\+?\\d{1,3}[-\\s]?\\(?\\d{1,4}\\)?[-\\s]?\\d{1,4}[-\\s]?\\d{1,9}$";75Pattern intlP→ ^\+?\d{1,3}[-\s]?\(?\d{1,4}\)?[-\s]?\d{1,4}[-\s]?\d{1,9}$ = Pattern.compile(intlPattern^\+?\d{1,3}[-\s]?\(?\d{1,4}\)?[-\s]?\d{1,4}[-\s]?\d{1,9}$);7677String[] intlPhones = {78 "+1 (555) 123-4567",79 "+44 20 7123 4567",80 "+81 3-1234-5678"81};8283System.out.println("\nInternational phones:");84for (String phone : intlPhones) {output International phones:valid ← true
pass 1 of 383System.out.println("\nInternational phones:");84for (String phone+1 (555) 123-4567 : intlPhones) {85 boolean valid→ true = intlP.matcher(phone+1 (555) 123-4567).matches();86 System.out.println(" " + phone+1 (555) 123-4567 + ": " + validtrue);87}output +1 (555) 123-4567: trueAll 3 passes — pass 1 is the card above pass phonevalid1 +1 (555) 123-4567 true 2 +44 20 7123 4567 true 3 +81 3-1234-5678 true
public static void main(String[] args)
8public static void main(String[] args) {9 // US phone formats10 String[] patterns = {11 "\\(\\d{3}\\)\\s\\d{3}-\\d{4}", // (123) 456-789012 "\\d{3}-\\d{3}-\\d{4}", // 123-456-789013 "\\d{10}" // 123456789014 };1516 String[] phones = {17 "(555) 123-4567",18 "555-123-4567",19 "5551234567",20 "(555)123-4567", // no space21 "555.123.4567",22 "invalid"23 };2425 System.out.println("Phone validation:");26 for (int i = 0; i < patterns.length; i++) {outputPhone validation:p ← \(\d{3}\)\s\d{3}-\d{4}
pass 1 of 325System.out.println("Phone validation:");26for (int i0 = 0; i < patterns.length3; i++) {27 System.out.println("\nPattern " + (i0+1) + ":");28 Pattern p→ \(\d{3}\)\s\d{3}-\d{4} = Pattern.compile(patterns[i]\(\d{3}\)\s\d{3}-\d{4});29 for (String phone : phones) {output Pattern 1:All 3 passes — pass 1 is the card above pass ipatterns[i]p1 0 \(\d{3}\)\s\d{3}-\d{4} \(\d{3}\)\s\d{3}-\d{4} 2 1 \d{3}-\d{3}-\d{4} \d{3}-\d{3}-\d{4} 3 2 \d{10} \d{10} valid ← true
pass 1 of 1828Pattern p = Pattern.compile(patterns[i]);29for (String phone(555) 123-4567 : phones) {30 boolean valid→ true = p.matcher(phone(555) 123-4567).matches();31 System.out.println(" " + phone(555) 123-4567 + ": " + validtrue);32}output (555) 123-4567: true18 passes — pass 1 is the card above pass phonevalid1 (555) 123-4567 true 2 555-123-4567 false 3 5551234567 false 4 (555)123-4567 false 5 555.123.4567 false 6 invalid false 7 (555) 123-4567 false 8 555-123-4567 true 9 5551234567 false ⋯ 7 more passes ⋯ 17 555.123.4567 false 18 invalid false anyFormat ← ^(\(\d{3}\)\s?|\d{3}-)?\d{3}-?\d{4}$, anyPattern ← ^(\(\d{3}\)\s?|\d{3}-)?\d{3}-?\d{4}$
35// Combined pattern (any format)36String anyFormat→ ^(\(\d{3}\)\s?|\d{3}-)?\d{3}-?\d{4}$ = "^(\\(\\d{3}\\)\\s?|\\d{3}-)?\\d{3}-?\\d{4}$";37Pattern anyPattern→ ^(\(\d{3}\)\s?|\d{3}-)?\d{3}-?\d{4}$ = Pattern.compile(anyFormat^(\(\d{3}\)\s?|\d{3}-)?\d{3}-?\d{4}$);3839System.out.println("\nCombined pattern:");40for (String phone : phones) {output Combined pattern:valid ← true
pass 1 of 639System.out.println("\nCombined pattern:");40for (String phone(555) 123-4567 : phones) {41 boolean valid→ true = anyPattern.matcher(phone(555) 123-4567).matches();42 System.out.println(" " + phone(555) 123-4567 + ": " + validtrue);43}output (555) 123-4567: trueAll 6 passes — pass 1 is the card above pass phonevalid1 (555) 123-4567 true 2 555-123-4567 true 3 5551234567 false 4 (555)123-4567 true 5 555.123.4567 false 6 invalid false extractPattern ← \((\d{3})\)\s(\d{3})-(\d{4}), extract ← \((\d{3})\)\s(\d{3})-(\d{4})
45// Extract phone parts46String extractPattern→ \((\d{3})\)\s(\d{3})-(\d{4}) = "\\((\\d{3})\\)\\s(\\d{3})-(\\d{4})";47Pattern extract→ \((\d{3})\)\s(\d{3})-(\d{4}) = Pattern.compile(extractPattern\((\d{3})\)\s(\d{3})-(\d{4}));4849String testPhone→ 555-123-4567 = "555-123-4567";50Matcher matcher→ java.util.regex.Matcher[pattern=\((\d{3})\)\s(\d{3})-(\d{4}) region=0,12 lastmatch=] = extract.matcher(testPhone555-123-4567);5152if (matcher.matches()) {53 System.out.println("\nExtracted parts from " + testPhone + ":");54 System.out.println(" Area code: " + matcher.group(1));55 System.out.println(" Exchange: " + matcher.group(2));56 System.out.println(" Number: " + matcher.group(3));57}5859// Find all phones in text60String text→ Call us at (555) 123-4567 or 555-987-6543. Emergency: (999) 911-0000 = """61 Call us at (555) 123-4567 or 555-987-6543.62 Emergency: (999) 911-000063 """;6465Pattern findPattern→ \(?\d{3}\)?[-\s]?\d{3}-\d{4} = Pattern.compile("\\(?\\d{3}\\)?[-\\s]?\\d{3}-\\d{4}");66Matcher findMatcher→ java.util.regex.Matcher[pattern=\(?\d{3}\)?[-\s]?\d{3}-\d{4} region=0,69 lastmatch=] = findPattern.matcher(textCall us at (555) 123-4567 or 555-987-6543. Emergency: (999) 911-0000 );6768System.out.println("\nPhones found in text:");69while (findMatcher.find()) {output Phones found in text:while (findMatcher.find())
pass 1 of 368System.out.println("\nPhones found in text:");69while (findMatcher.find()) {70 System.out.println(" " + findMatcher.group());71}output (555) 123-4567intlPattern ← ^\+?\d{1,3}[-\s]?\(?\d{1,4}\)?[-\s]?\d{1,4}[-\s]?\d{1,9}$
73// International format (basic)74String intlPattern→ ^\+?\d{1,3}[-\s]?\(?\d{1,4}\)?[-\s]?\d{1,4}[-\s]?\d{1,9}$ = "^\\+?\\d{1,3}[-\\s]?\\(?\\d{1,4}\\)?[-\\s]?\\d{1,4}[-\\s]?\\d{1,9}$";75Pattern intlP→ ^\+?\d{1,3}[-\s]?\(?\d{1,4}\)?[-\s]?\d{1,4}[-\s]?\d{1,9}$ = Pattern.compile(intlPattern^\+?\d{1,3}[-\s]?\(?\d{1,4}\)?[-\s]?\d{1,4}[-\s]?\d{1,9}$);7677String[] intlPhones = {78 "+1 (555) 123-4567",79 "+44 20 7123 4567",80 "+81 3-1234-5678"81};8283System.out.println("\nInternational phones:");84for (String phone : intlPhones) {output International phones:valid ← true
pass 1 of 383System.out.println("\nInternational phones:");84for (String phone+1 (555) 123-4567 : intlPhones) {85 boolean valid→ true = intlP.matcher(phone+1 (555) 123-4567).matches();86 System.out.println(" " + phone+1 (555) 123-4567 + ": " + validtrue);87}output +1 (555) 123-4567: trueAll 3 passes — pass 1 is the card above pass phonevalid1 +1 (555) 123-4567 true 2 +44 20 7123 4567 true 3 +81 3-1234-5678 true
phone_pattern
A phone pattern can match common formats such as parenthesized area codes, hyphen-separated numbers, and compact digit-only values.
URL Validation
Url.java
Replay: real traced execution (multi-file project)
// URL patterns
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Url {
public static void main(String[] args) {
// Basic URL pattern
String urlPattern = "^https?://[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}.*$";
String[] urls = {
"https://example.com",
"http://www.example.com",
"https://sub.example.co.uk",
"https://example.com/path",
"https://example.com/path?key=value",
"ftp://example.com", // wrong protocol
"example.com", // missing protocol
"https://localhost" // no TLD
};
System.out.println("URL validation:");
Pattern pattern = Pattern.compile(urlPattern);
for (String url : urls) {
boolean valid = pattern.matcher(url).matches();
System.out.println(" " + url + ": " + valid);
}
// Extract URL parts
String extractPattern = "^(https?)://([a-zA-Z0-9.-]+)(/.*)?$";
Pattern extractP = Pattern.compile(extractPattern);
String testUrl = "https://www.example.com/path/to/page";
Matcher matcher = extractP.matcher(testUrl);
if (matcher.matches()) {
System.out.println("\nExtracted parts from " + testUrl + ":");
System.out.println(" Protocol: " + matcher.group(1));
System.out.println(" Domain: " + matcher.group(2));
System.out.println(" Path: " + (matcher.group(3) != null ? matcher.group(3) : "/"));
}
// More detailed extraction
String detailPattern = "^(https?)://([^:/]+)(:(\\d+))?(/.*)?$";
Pattern detailP = Pattern.compile(detailPattern);
String[] testUrls = {
"https://example.com:8080/path",
"http://localhost:3000/api",
"https://example.com/page"
};
System.out.println("\nDetailed URL parsing:");
for (String url : testUrls) {
Matcher m = detailP.matcher(url);
if (m.matches()) {
System.out.println(" " + url);
System.out.println(" Protocol: " + m.group(1));
System.out.println(" Host: " + m.group(2));
System.out.println(" Port: " + (m.group(4) != null ? m.group(4) : "default"));
System.out.println(" Path: " + (m.group(5) != null ? m.group(5) : "/"));
}
}
// Find all URLs in text
String text = """
Visit https://example.com for more info.
Check out http://test.org/page and https://another.site/path?q=search
""";
Pattern findPattern = Pattern.compile("https?://[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}[^\\s]*");
Matcher findMatcher = findPattern.matcher(text);
System.out.println("\nURLs found in text:");
while (findMatcher.find()) {
System.out.println(" " + findMatcher.group());
}
// Query parameters
String queryPattern = "[?&]([^=]+)=([^&]+)";
String urlWithQuery = "https://example.com/search?q=regex&lang=java&page=1";
Pattern queryP = Pattern.compile(queryPattern);
Matcher queryM = queryP.matcher(urlWithQuery);
System.out.println("\nQuery parameters from: " + urlWithQuery);
while (queryM.find()) {
System.out.println(" " + queryM.group(1) + " = " + queryM.group(2));
}
}
}
// URL patterns
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Url {
public static void main(String[] args) {
// Basic URL pattern
String urlPattern = "^https?://[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}.*$";
String[] urls = {
"https://example.com",
"http://www.example.com",
"https://sub.example.co.uk",
"https://example.com/path",
"https://example.com/path?key=value",
"ftp://example.com", // wrong protocol
"example.com", // missing protocol
"https://localhost" // no TLD
};
System.out.println("URL validation:");
Pattern pattern = Pattern.compile(urlPattern);
for (String url : urls) {
boolean valid = pattern.matcher(url).matches();
System.out.println(" " + url + ": " + valid);
}
// Extract URL parts
String extractPattern = "^(https?)://([a-zA-Z0-9.-]+)(/.*)?$";
Pattern extractP = Pattern.compile(extractPattern);
String testUrl = "http://example.org";
Matcher matcher = extractP.matcher(testUrl);
if (matcher.matches()) {
System.out.println("\nExtracted parts from " + testUrl + ":");
System.out.println(" Protocol: " + matcher.group(1));
System.out.println(" Domain: " + matcher.group(2));
System.out.println(" Path: " + (matcher.group(3) != null ? matcher.group(3) : "/"));
}
// More detailed extraction
String detailPattern = "^(https?)://([^:/]+)(:(\\d+))?(/.*)?$";
Pattern detailP = Pattern.compile(detailPattern);
String[] testUrls = {
"https://example.com:8080/path",
"http://localhost:3000/api",
"https://example.com/page"
};
System.out.println("\nDetailed URL parsing:");
for (String url : testUrls) {
Matcher m = detailP.matcher(url);
if (m.matches()) {
System.out.println(" " + url);
System.out.println(" Protocol: " + m.group(1));
System.out.println(" Host: " + m.group(2));
System.out.println(" Port: " + (m.group(4) != null ? m.group(4) : "default"));
System.out.println(" Path: " + (m.group(5) != null ? m.group(5) : "/"));
}
}
// Find all URLs in text
String text = """
Visit https://example.com for more info.
Check out http://test.org/page and https://another.site/path?q=search
""";
Pattern findPattern = Pattern.compile("https?://[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}[^\\s]*");
Matcher findMatcher = findPattern.matcher(text);
System.out.println("\nURLs found in text:");
while (findMatcher.find()) {
System.out.println(" " + findMatcher.group());
}
// Query parameters
String queryPattern = "[?&]([^=]+)=([^&]+)";
String urlWithQuery = "https://example.com/search?q=regex&lang=java&page=1";
Pattern queryP = Pattern.compile(queryPattern);
Matcher queryM = queryP.matcher(urlWithQuery);
System.out.println("\nQuery parameters from: " + urlWithQuery);
while (queryM.find()) {
System.out.println(" " + queryM.group(1) + " = " + queryM.group(2));
}
}
}
urlPattern ← ^https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}.*$, pattern ← ^https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}.*$
8public static void main(String[] args) {9 // Basic URL pattern10 String urlPattern→ ^https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}.*$ = "^https?://[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}.*$";11 12 String[] urls = {13 "https://example.com",14 "http://www.example.com",15 "https://sub.example.co.uk",16 "https://example.com/path",17 "https://example.com/path?key=value",18 "ftp://example.com", // wrong protocol19 "example.com", // missing protocol20 "https://localhost" // no TLD21 };2223 System.out.println("URL validation:");24 Pattern pattern→ ^https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}.*$ = Pattern.compile(urlPattern^https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}.*$);25 for (String url : urls) {outputURL validation:valid ← true
pass 1 of 824Pattern pattern = Pattern.compile(urlPattern);25for (String urlhttps://example.com : urls) {26 boolean valid→ true = pattern.matcher(urlhttps://example.com).matches();27 System.out.println(" " + urlhttps://example.com + ": " + validtrue);28}output https://example.com: trueAll 8 passes — pass 1 is the card above pass urlvalid1 https://example.com true 2 http://www.example.com true 3 https://sub.example.co.uk true 4 https://example.com/path true 5 https://example.com/path?key=value true 6 ftp://example.com false 7 example.com false 8 https://localhost false extractPattern ← ^(https?)://([a-zA-Z0-9.-]+)(/.*)?$, extractP ← ^(https?)://([a-zA-Z0-9.-]+)(/.*)?$
30// Extract URL parts31String extractPattern→ ^(https?)://([a-zA-Z0-9.-]+)(/.*)?$ = "^(https?)://([a-zA-Z0-9.-]+)(/.*)?$";32Pattern extractP→ ^(https?)://([a-zA-Z0-9.-]+)(/.*)?$ = Pattern.compile(extractPattern^(https?)://([a-zA-Z0-9.-]+)(/.*)?$);3334String testUrl→ https://www.example.com/path/to/page = "https://www.example.com/path/to/page"; //@testUrl="https://www.example.com/path/to/page", "http://example.org"35Matcher matcher→ java.util.regex.Matcher[pattern=^(https?)://([a-zA-Z0-9.-]+)(/.*)?$ region=0,36 lastmatch=] = extractP.matcher(testUrlhttps://www.example.com/path/to/page);if (matcher.matches())
37if (matcher.matches()) {38 System.out.println("\nExtracted parts from " + testUrlhttps://www.example.com/path/to/page + ":");39 System.out.println(" Protocol: " + matcher.group(1));40 System.out.println(" Domain: " + matcher.group(2));41 System.out.println(" Path: " + (matcher.group(3) != null ? matcher.group(3) : "/"));42}output Extracted parts from https://www.example.com/path/to/page: Protocol: https Domain: www.example.com Path: /path/to/pagedetailPattern ← ^(https?)://([^:/]+)(:(\d+))?(/.*)?$, detailP ← ^(https?)://([^:/]+)(:(\d+))?(/.*)?$
44// More detailed extraction45String detailPattern→ ^(https?)://([^:/]+)(:(\d+))?(/.*)?$ = "^(https?)://([^:/]+)(:(\\d+))?(/.*)?$";46Pattern detailP→ ^(https?)://([^:/]+)(:(\d+))?(/.*)?$ = Pattern.compile(detailPattern^(https?)://([^:/]+)(:(\d+))?(/.*)?$);4748String[] testUrls = {49 "https://example.com:8080/path",50 "http://localhost:3000/api",51 "https://example.com/page"52};5354System.out.println("\nDetailed URL parsing:");55for (String url : testUrls) {output Detailed URL parsing:m ← java.util.regex.Matcher[pattern=^(https?)://([^:/]+)(:(\d+))?(/.*)?$ region=0,29 lastmatch=]
pass 1 of 354System.out.println("\nDetailed URL parsing:");55for (String urlhttps://example.com:8080/path : testUrls) {56 Matcher m→ java.util.regex.Matcher[pattern=^(https?)://([^:/]+)(:(\d+))?(/.*)?$ region=0,29 lastmatch=] = detailP.matcher(urlhttps://example.com:8080/path);57 if (m.matches()) {All 3 passes — pass 1 is the card above pass urlm1 https://example.com:8080/path java.util.regex.Matcher[pattern=^(https?)://([^:/]+)(:(\d+))?(/.*)?$ region=0,29 lastmatch=] 2 http://localhost:3000/api java.util.regex.Matcher[pattern=^(https?)://([^:/]+)(:(\d+))?(/.*)?$ region=0,25 lastmatch=] 3 https://example.com/page java.util.regex.Matcher[pattern=^(https?)://([^:/]+)(:(\d+))?(/.*)?$ region=0,24 lastmatch=] if (m.matches())
pass 1 of 356Matcher m = detailP.matcher(url);57if (m.matches()) {58 System.out.println(" " + urlhttps://example.com:8080/path);59 System.out.println(" Protocol: " + m.group(1));60 System.out.println(" Host: " + m.group(2));61 System.out.println(" Port: " + (m.group(4) != null ? m.group(4) : "default"));62 System.out.println(" Path: " + (m.group(5) != null ? m.group(5) : "/"));63}output https://example.com:8080/path Protocol: https Host: example.com Port: 8080 Path: /pathAll 3 passes — pass 1 is the card above pass url1 https://example.com:8080/path 2 http://localhost:3000/api 3 https://example.com/page text ← Visit https://example.com for more info. Check out http://test.org/page and https://another.site/path?q=search
66// Find all URLs in text67String text→ Visit https://example.com for more info. Check out http://test.org/page and https://another.site/path?q=search = """68 Visit https://example.com for more info.69 Check out http://test.org/page and https://another.site/path?q=search70 """;7172Pattern findPattern→ https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}[^\s]* = Pattern.compile("https?://[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}[^\\s]*");73Matcher findMatcher→ java.util.regex.Matcher[pattern=https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}[^\s]* region=0,111 lastmatch=] = findPattern.matcher(textVisit https://example.com for more info. Check out http://test.org/page and https://another.site/path?q=search );7475System.out.println("\nURLs found in text:");76while (findMatcher.find()) {output URLs found in text:while (findMatcher.find())
pass 1 of 375System.out.println("\nURLs found in text:");76while (findMatcher.find()) {77 System.out.println(" " + findMatcher.group());78}output https://example.comqueryPattern ← [?&]([^=]+)=([^&]+), urlWithQuery ← https://example.com/search?q=regex&lang=java&page=1
80// Query parameters81String queryPattern→ [?&]([^=]+)=([^&]+) = "[?&]([^=]+)=([^&]+)";82String urlWithQuery→ https://example.com/search?q=regex&lang=java&page=1 = "https://example.com/search?q=regex&lang=java&page=1";8384Pattern queryP→ [?&]([^=]+)=([^&]+) = Pattern.compile(queryPattern[?&]([^=]+)=([^&]+));85Matcher queryM→ java.util.regex.Matcher[pattern=[?&]([^=]+)=([^&]+) region=0,51 lastmatch=] = queryP.matcher(urlWithQueryhttps://example.com/search?q=regex&lang=java&page=1);8687System.out.println("\nQuery parameters from: " + urlWithQueryhttps://example.com/search?q=regex&lang=java&page=1);88while (queryM.find()) {output Query parameters from: https://example.com/search?q=regex&lang=java&page=1while (queryM.find())
pass 1 of 387System.out.println("\nQuery parameters from: " + urlWithQuery);88while (queryM.find()) {89 System.out.println(" " + queryM.group(1) + " = " + queryM.group(2));90}output q = regex
urlPattern ← ^https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}.*$, pattern ← ^https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}.*$
8public static void main(String[] args) {9 // Basic URL pattern10 String urlPattern→ ^https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}.*$ = "^https?://[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}.*$";11 12 String[] urls = {13 "https://example.com",14 "http://www.example.com",15 "https://sub.example.co.uk",16 "https://example.com/path",17 "https://example.com/path?key=value",18 "ftp://example.com", // wrong protocol19 "example.com", // missing protocol20 "https://localhost" // no TLD21 };2223 System.out.println("URL validation:");24 Pattern pattern→ ^https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}.*$ = Pattern.compile(urlPattern^https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}.*$);25 for (String url : urls) {outputURL validation:valid ← true
pass 1 of 824Pattern pattern = Pattern.compile(urlPattern);25for (String urlhttps://example.com : urls) {26 boolean valid→ true = pattern.matcher(urlhttps://example.com).matches();27 System.out.println(" " + urlhttps://example.com + ": " + validtrue);28}output https://example.com: trueAll 8 passes — pass 1 is the card above pass urlvalid1 https://example.com true 2 http://www.example.com true 3 https://sub.example.co.uk true 4 https://example.com/path true 5 https://example.com/path?key=value true 6 ftp://example.com false 7 example.com false 8 https://localhost false extractPattern ← ^(https?)://([a-zA-Z0-9.-]+)(/.*)?$, extractP ← ^(https?)://([a-zA-Z0-9.-]+)(/.*)?$
30// Extract URL parts31String extractPattern→ ^(https?)://([a-zA-Z0-9.-]+)(/.*)?$ = "^(https?)://([a-zA-Z0-9.-]+)(/.*)?$";32Pattern extractP→ ^(https?)://([a-zA-Z0-9.-]+)(/.*)?$ = Pattern.compile(extractPattern^(https?)://([a-zA-Z0-9.-]+)(/.*)?$);3334String testUrl→ http://example.org = "http://example.org";35Matcher matcher→ java.util.regex.Matcher[pattern=^(https?)://([a-zA-Z0-9.-]+)(/.*)?$ region=0,18 lastmatch=] = extractP.matcher(testUrlhttp://example.org);if (matcher.matches())
37if (matcher.matches()) {38 System.out.println("\nExtracted parts from " + testUrlhttp://example.org + ":");39 System.out.println(" Protocol: " + matcher.group(1));40 System.out.println(" Domain: " + matcher.group(2));41 System.out.println(" Path: " + (matcher.group(3) != null ? matcher.group(3) : "/"));42}output Extracted parts from http://example.org: Protocol: http Domain: example.org Path: /detailPattern ← ^(https?)://([^:/]+)(:(\d+))?(/.*)?$, detailP ← ^(https?)://([^:/]+)(:(\d+))?(/.*)?$
44// More detailed extraction45String detailPattern→ ^(https?)://([^:/]+)(:(\d+))?(/.*)?$ = "^(https?)://([^:/]+)(:(\\d+))?(/.*)?$";46Pattern detailP→ ^(https?)://([^:/]+)(:(\d+))?(/.*)?$ = Pattern.compile(detailPattern^(https?)://([^:/]+)(:(\d+))?(/.*)?$);4748String[] testUrls = {49 "https://example.com:8080/path",50 "http://localhost:3000/api",51 "https://example.com/page"52};5354System.out.println("\nDetailed URL parsing:");55for (String url : testUrls) {output Detailed URL parsing:m ← java.util.regex.Matcher[pattern=^(https?)://([^:/]+)(:(\d+))?(/.*)?$ region=0,29 lastmatch=]
pass 1 of 354System.out.println("\nDetailed URL parsing:");55for (String urlhttps://example.com:8080/path : testUrls) {56 Matcher m→ java.util.regex.Matcher[pattern=^(https?)://([^:/]+)(:(\d+))?(/.*)?$ region=0,29 lastmatch=] = detailP.matcher(urlhttps://example.com:8080/path);57 if (m.matches()) {All 3 passes — pass 1 is the card above pass urlm1 https://example.com:8080/path java.util.regex.Matcher[pattern=^(https?)://([^:/]+)(:(\d+))?(/.*)?$ region=0,29 lastmatch=] 2 http://localhost:3000/api java.util.regex.Matcher[pattern=^(https?)://([^:/]+)(:(\d+))?(/.*)?$ region=0,25 lastmatch=] 3 https://example.com/page java.util.regex.Matcher[pattern=^(https?)://([^:/]+)(:(\d+))?(/.*)?$ region=0,24 lastmatch=] if (m.matches())
pass 1 of 356Matcher m = detailP.matcher(url);57if (m.matches()) {58 System.out.println(" " + urlhttps://example.com:8080/path);59 System.out.println(" Protocol: " + m.group(1));60 System.out.println(" Host: " + m.group(2));61 System.out.println(" Port: " + (m.group(4) != null ? m.group(4) : "default"));62 System.out.println(" Path: " + (m.group(5) != null ? m.group(5) : "/"));63}output https://example.com:8080/path Protocol: https Host: example.com Port: 8080 Path: /pathAll 3 passes — pass 1 is the card above pass url1 https://example.com:8080/path 2 http://localhost:3000/api 3 https://example.com/page text ← Visit https://example.com for more info. Check out http://test.org/page and https://another.site/path?q=search
66// Find all URLs in text67String text→ Visit https://example.com for more info. Check out http://test.org/page and https://another.site/path?q=search = """68 Visit https://example.com for more info.69 Check out http://test.org/page and https://another.site/path?q=search70 """;7172Pattern findPattern→ https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}[^\s]* = Pattern.compile("https?://[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}[^\\s]*");73Matcher findMatcher→ java.util.regex.Matcher[pattern=https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}[^\s]* region=0,111 lastmatch=] = findPattern.matcher(textVisit https://example.com for more info. Check out http://test.org/page and https://another.site/path?q=search );7475System.out.println("\nURLs found in text:");76while (findMatcher.find()) {output URLs found in text:while (findMatcher.find())
pass 1 of 375System.out.println("\nURLs found in text:");76while (findMatcher.find()) {77 System.out.println(" " + findMatcher.group());78}output https://example.comqueryPattern ← [?&]([^=]+)=([^&]+), urlWithQuery ← https://example.com/search?q=regex&lang=java&page=1
80// Query parameters81String queryPattern→ [?&]([^=]+)=([^&]+) = "[?&]([^=]+)=([^&]+)";82String urlWithQuery→ https://example.com/search?q=regex&lang=java&page=1 = "https://example.com/search?q=regex&lang=java&page=1";8384Pattern queryP→ [?&]([^=]+)=([^&]+) = Pattern.compile(queryPattern[?&]([^=]+)=([^&]+));85Matcher queryM→ java.util.regex.Matcher[pattern=[?&]([^=]+)=([^&]+) region=0,51 lastmatch=] = queryP.matcher(urlWithQueryhttps://example.com/search?q=regex&lang=java&page=1);8687System.out.println("\nQuery parameters from: " + urlWithQueryhttps://example.com/search?q=regex&lang=java&page=1);88while (queryM.find()) {output Query parameters from: https://example.com/search?q=regex&lang=java&page=1while (queryM.find())
pass 1 of 387System.out.println("\nQuery parameters from: " + urlWithQuery);88while (queryM.find()) {89 System.out.println(" " + queryM.group(1) + " = " + queryM.group(2));90}output q = regex
url_pattern
A URL pattern can capture a protocol, host, optional port, path, and query string.
Extraction Operations
Extraction.java
Replay: real traced execution (multi-file project)
// Text extraction with regex
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.ArrayList;
import java.util.List;
public class Extraction {
public static List<String> extractHashtags(String text) {
List<String> hashtags = new ArrayList<>();
Pattern pattern = Pattern.compile("#\\w+");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
hashtags.add(matcher.group());
}
return hashtags;
}
public static List<String> extractMentions(String text) {
List<String> mentions = new ArrayList<>();
Pattern pattern = Pattern.compile("@\\w+");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
mentions.add(matcher.group());
}
return mentions;
}
public static List<Double> extractNumbers(String text) {
List<Double> numbers = new ArrayList<>();
Pattern pattern = Pattern.compile("-?\\d+\\.?\\d*");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
numbers.add(Double.parseDouble(matcher.group()));
}
return numbers;
}
public static List<String> extractDates(String text) {
List<String> dates = new ArrayList<>();
// YYYY-MM-DD format
Pattern pattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
dates.add(matcher.group());
}
return dates;
}
public static void main(String[] args) {
// Social media text
String tweet = """
Loving #java and #regex! Thanks @copilot for the help.
Check out #programming tips at https://example.com
Mentions: @user1 @user2 #coding
""";
System.out.println("Social media extraction:");
System.out.println("Hashtags: " + extractHashtags(tweet));
System.out.println("Mentions: " + extractMentions(tweet));
// Numbers
String dataText = "Prices: $19.99, $5.50, and $100. Temperature: -5.5°C";
System.out.println("\nNumbers extraction:");
System.out.println("Numbers: " + extractNumbers(dataText));
// Dates
String logText = """
2025-01-29: Error occurred
2025-01-30: Fixed bug
2025-02-01: Deployed
""";
System.out.println("\nDates extraction:");
System.out.println("Dates: " + extractDates(logText));
// IP addresses
String serverLog = "Requests from 192.168.1.1, 10.0.0.5, and 172.16.0.10";
Pattern ipPattern = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
Matcher ipMatcher = ipPattern.matcher(serverLog);
System.out.println("\nIP addresses:");
while (ipMatcher.find()) {
System.out.println(" " + ipMatcher.group());
}
// Extract quoted strings
String quoteText = "He said \"Hello\" and she replied \"Hi there!\"";
Pattern quotePattern = Pattern.compile("\"([^\"]+)\"");
Matcher quoteMatcher = quotePattern.matcher(quoteText);
System.out.println("\nQuoted strings:");
while (quoteMatcher.find()) {
System.out.println(" " + quoteMatcher.group(1));
}
// Key-value pairs
String config = "name=John age=30 city=NYC email=john@example.com";
Pattern kvPattern = Pattern.compile("(\\w+)=(\\S+)");
Matcher kvMatcher = kvPattern.matcher(config);
System.out.println("\nKey-value pairs:");
while (kvMatcher.find()) {
System.out.println(" " + kvMatcher.group(1) + " = " + kvMatcher.group(2));
}
// HTML tags (simple)
String html = "<div>Content</div><span>Text</span>";
Pattern tagPattern = Pattern.compile("<(\\w+)>([^<]+)</\\1>");
Matcher tagMatcher = tagPattern.matcher(html);
System.out.println("\nHTML content:");
while (tagMatcher.find()) {
System.out.println(" <" + tagMatcher.group(1) + ">: " + tagMatcher.group(2));
}
}
}
// Text extraction with regex
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.ArrayList;
import java.util.List;
public class Extraction {
public static List<String> extractHashtags(String text) {
List<String> hashtags = new ArrayList<>();
Pattern pattern = Pattern.compile("#\\w+");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
hashtags.add(matcher.group());
}
return hashtags;
}
public static List<String> extractMentions(String text) {
List<String> mentions = new ArrayList<>();
Pattern pattern = Pattern.compile("@\\w+");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
mentions.add(matcher.group());
}
return mentions;
}
public static List<Double> extractNumbers(String text) {
List<Double> numbers = new ArrayList<>();
Pattern pattern = Pattern.compile("-?\\d+\\.?\\d*");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
numbers.add(Double.parseDouble(matcher.group()));
}
return numbers;
}
public static List<String> extractDates(String text) {
List<String> dates = new ArrayList<>();
// YYYY-MM-DD format
Pattern pattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
dates.add(matcher.group());
}
return dates;
}
public static void main(String[] args) {
// Social media text
String tweet = """
Loving #java and #regex! Thanks @copilot for the help.
Check out #programming tips at https://example.com
Mentions: @user1 @user2 #coding
""";
System.out.println("Social media extraction:");
System.out.println("Hashtags: " + extractHashtags(tweet));
System.out.println("Mentions: " + extractMentions(tweet));
// Numbers
String dataText = "Prices: $19.99, $5.50, and $100. Temperature: -5.5°C";
System.out.println("\nNumbers extraction:");
System.out.println("Numbers: " + extractNumbers(dataText));
// Dates
String logText = """
2025-01-29: Error occurred
2025-01-30: Fixed bug
2025-02-01: Deployed
""";
System.out.println("\nDates extraction:");
System.out.println("Dates: " + extractDates(logText));
// IP addresses
String serverLog = "Requests from 192.168.1.1, 10.0.0.5, and 172.16.0.10";
Pattern ipPattern = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
Matcher ipMatcher = ipPattern.matcher(serverLog);
System.out.println("\nIP addresses:");
while (ipMatcher.find()) {
System.out.println(" " + ipMatcher.group());
}
// Extract quoted strings
String quoteText = "He said \"Hello\" and she replied \"Hi there!\"";
Pattern quotePattern = Pattern.compile("\"([^\"]+)\"");
Matcher quoteMatcher = quotePattern.matcher(quoteText);
System.out.println("\nQuoted strings:");
while (quoteMatcher.find()) {
System.out.println(" " + quoteMatcher.group(1));
}
// Key-value pairs
String config = "name=Ada role=admin city=London";
Pattern kvPattern = Pattern.compile("(\\w+)=(\\S+)");
Matcher kvMatcher = kvPattern.matcher(config);
System.out.println("\nKey-value pairs:");
while (kvMatcher.find()) {
System.out.println(" " + kvMatcher.group(1) + " = " + kvMatcher.group(2));
}
// HTML tags (simple)
String html = "<div>Content</div><span>Text</span>";
Pattern tagPattern = Pattern.compile("<(\\w+)>([^<]+)</\\1>");
Matcher tagMatcher = tagPattern.matcher(html);
System.out.println("\nHTML content:");
while (tagMatcher.find()) {
System.out.println(" <" + tagMatcher.group(1) + ">: " + tagMatcher.group(2));
}
}
}
tweet ← Loving #java and #regex! Thanks @copilot for the help. Check out #programming tips at https://example.com Mentions: @user1 @user2 #coding
55public static void main(String[] args) {56 // Social media text57 String tweet→ Loving #java and #regex! Thanks @copilot for the help. Check out #programming tips at https://example.com Mentions: @user1 @user2 #coding = """58 Loving #java and #regex! Thanks @copilot for the help.59 Check out #programming tips at https://example.com60 Mentions: @user1 @user2 #coding61 """;6263 System.out.println("Social media extraction:");64 System.out.println("Hashtags: " + extractHashtags(tweetLoving #java and #regex! Thanks @copilot for the help. Check out #programming tips at https://example.com Mentions: @user1 @user2 #coding ));65 System.out.println("Mentions: " + extractMentions(tweet));outputSocial media extraction:hashtags ← [], pattern ← #\w+, matcher ← java.util.regex.Matcher[pattern=#\w+ region=0,138 lastmatch=]
10public static List<String> extractHashtags(String textLoving #java and #regex! Thanks @copilot for the help. Check out #programming tips at https://example.com Mentions: @user1 @user2 #coding ) {11 List<String> hashtags→ [] = new ArrayList<>();12 Pattern pattern→ #\w+ = Pattern.compile("#\\w+");13 Matcher matcher→ java.util.regex.Matcher[pattern=#\w+ region=0,138 lastmatch=] = pattern.matcher(textLoving #java and #regex! Thanks @copilot for the help. Check out #programming tips at https://example.com Mentions: @user1 @user2 #coding );return hashtags;
17 }18 return hashtags[#java, #regex, #programming, #coding];19}System.out.println("Hashtags: " + extractHashtags(tweet));
63System.out.println("Social media extraction:");64System.out.println("Hashtags: " + extractHashtags(tweetLoving #java and #regex! Thanks @copilot for the help. Check out #programming tips at https://example.com Mentions: @user1 @user2 #coding ));65System.out.println("Mentions: " + extractMentions(tweetLoving #java and #regex! Thanks @copilot for the help. Check out #programming tips at https://example.com Mentions: @user1 @user2 #coding ));outputHashtags: [#java, #regex, #programming, #coding]mentions ← [], pattern ← @\w+, matcher ← java.util.regex.Matcher[pattern=@\w+ region=0,138 lastmatch=]
21public static List<String> extractMentions(String textLoving #java and #regex! Thanks @copilot for the help. Check out #programming tips at https://example.com Mentions: @user1 @user2 #coding ) {22 List<String> mentions→ [] = new ArrayList<>();23 Pattern pattern→ @\w+ = Pattern.compile("@\\w+");24 Matcher matcher→ java.util.regex.Matcher[pattern=@\w+ region=0,138 lastmatch=] = pattern.matcher(textLoving #java and #regex! Thanks @copilot for the help. Check out #programming tips at https://example.com Mentions: @user1 @user2 #coding );return mentions;
28 }29 return mentions[@copilot, @user1, @user2];30}dataText ← Prices: $19.99, $5.50, and $100. Temperature: -5.5°C
64System.out.println("Hashtags: " + extractHashtags(tweet));65System.out.println("Mentions: " + extractMentions(tweetLoving #java and #regex! Thanks @copilot for the help. Check out #programming tips at https://example.com Mentions: @user1 @user2 #coding ));6667// Numbers68String dataText→ Prices: $19.99, $5.50, and $100. Temperature: -5.5°C = "Prices: $19.99, $5.50, and $100. Temperature: -5.5°C";69System.out.println("\nNumbers extraction:");70System.out.println("Numbers: " + extractNumbers(dataTextPrices: $19.99, $5.50, and $100. Temperature: -5.5°C));outputMentions: [@copilot, @user1, @user2] Numbers extraction:numbers ← [], pattern ← -?\d+\.?\d*, matcher ← java.util.regex.Matcher[pattern=-?\d+\.?\d* region=0,52 lastmatch=]
32public static List<Double> extractNumbers(String textPrices: $19.99, $5.50, and $100. Temperature: -5.5°C) {33 List<Double> numbers→ [] = new ArrayList<>();34 Pattern pattern→ -?\d+\.?\d* = Pattern.compile("-?\\d+\\.?\\d*");35 Matcher matcher→ java.util.regex.Matcher[pattern=-?\d+\.?\d* region=0,52 lastmatch=] = pattern.matcher(textPrices: $19.99, $5.50, and $100. Temperature: -5.5°C);return numbers;
39 }40 return numbers[19.99, 5.5, 100.0, -5.5];41}logText ← 2025-01-29: Error occurred 2025-01-30: Fixed bug 2025-02-01: Deployed
69System.out.println("\nNumbers extraction:");70System.out.println("Numbers: " + extractNumbers(dataTextPrices: $19.99, $5.50, and $100. Temperature: -5.5°C));7172// Dates73String logText→ 2025-01-29: Error occurred 2025-01-30: Fixed bug 2025-02-01: Deployed = """74 2025-01-29: Error occurred75 2025-01-30: Fixed bug76 2025-02-01: Deployed77 """;78System.out.println("\nDates extraction:");79System.out.println("Dates: " + extractDates(logText2025-01-29: Error occurred 2025-01-30: Fixed bug 2025-02-01: Deployed ));outputNumbers: [19.99, 5.5, 100.0, -5.5] Dates extraction:dates ← [], pattern ← \d{4}-\d{2}-\d{2}, matcher ← java.util.regex.Matcher[pattern=\d{4}-\d{2}-\d{2} region=0,70 lastmatch=]
43public static List<String> extractDates(String text2025-01-29: Error occurred 2025-01-30: Fixed bug 2025-02-01: Deployed ) {44 List<String> dates→ [] = new ArrayList<>();45 // YYYY-MM-DD format46 Pattern pattern→ \d{4}-\d{2}-\d{2} = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");47 Matcher matcher→ java.util.regex.Matcher[pattern=\d{4}-\d{2}-\d{2} region=0,70 lastmatch=] = pattern.matcher(text2025-01-29: Error occurred 2025-01-30: Fixed bug 2025-02-01: Deployed );return dates;
51 }52 return dates[2025-01-29, 2025-01-30, 2025-02-01];53}serverLog ← Requests from 192.168.1.1, 10.0.0.5, and 172.16.0.10
78System.out.println("\nDates extraction:");79System.out.println("Dates: " + extractDates(logText2025-01-29: Error occurred 2025-01-30: Fixed bug 2025-02-01: Deployed ));8081// IP addresses82String serverLog→ Requests from 192.168.1.1, 10.0.0.5, and 172.16.0.10 = "Requests from 192.168.1.1, 10.0.0.5, and 172.16.0.10";83Pattern ipPattern→ \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");84Matcher ipMatcher→ java.util.regex.Matcher[pattern=\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} region=0,52 lastmatch=] = ipPattern.matcher(serverLogRequests from 192.168.1.1, 10.0.0.5, and 172.16.0.10);8586System.out.println("\nIP addresses:");87while (ipMatcher.find()) {outputDates: [2025-01-29, 2025-01-30, 2025-02-01] IP addresses:while (ipMatcher.find())
pass 1 of 386System.out.println("\nIP addresses:");87while (ipMatcher.find()) {88 System.out.println(" " + ipMatcher.group());89}output 192.168.1.1quoteText ← He said "Hello" and she replied "Hi there!", quotePattern ← "([^"]+)"
91// Extract quoted strings92String quoteText→ He said "Hello" and she replied "Hi there!" = "He said \"Hello\" and she replied \"Hi there!\"";93Pattern quotePattern→ "([^"]+)" = Pattern.compile("\"([^\"]+)\"");94Matcher quoteMatcher→ java.util.regex.Matcher[pattern="([^"]+)" region=0,43 lastmatch=] = quotePattern.matcher(quoteTextHe said "Hello" and she replied "Hi there!");9596System.out.println("\nQuoted strings:");97while (quoteMatcher.find()) {output Quoted strings:while (quoteMatcher.find())
pass 1 of 296System.out.println("\nQuoted strings:");97while (quoteMatcher.find()) {98 System.out.println(" " + quoteMatcher.group(1));99}output Hellowhile (quoteMatcher.find())
pass 2 of 296System.out.println("\nQuoted strings:");97while (quoteMatcher.find()) {98 System.out.println(" " + quoteMatcher.group(1));99}output Hi there!config ← name=John age=30 city=NYC email=john@example.com, kvPattern ← (\w+)=(\S+)
101// Key-value pairs102String config→ name=John age=30 city=NYC email=john@example.com = "name=John age=30 city=NYC email=john@example.com"; //@config="name=John age=30 city=NYC email=john@example.com", "name=Ada role=admin city=London"103Pattern kvPattern→ (\w+)=(\S+) = Pattern.compile("(\\w+)=(\\S+)");104Matcher kvMatcher→ java.util.regex.Matcher[pattern=(\w+)=(\S+) region=0,48 lastmatch=] = kvPattern.matcher(configname=John age=30 city=NYC email=john@example.com);105106System.out.println("\nKey-value pairs:");107while (kvMatcher.find()) {output Key-value pairs:while (kvMatcher.find())
pass 1 of 4106System.out.println("\nKey-value pairs:");107while (kvMatcher.find()) {108 System.out.println(" " + kvMatcher.group(1) + " = " + kvMatcher.group(2));109}output name = Johnhtml ← <div>Content</div><span>Text</span>, tagPattern ← <(\w+)>([^<]+)</\1>
111// HTML tags (simple)112String html→ <div>Content</div><span>Text</span> = "<div>Content</div><span>Text</span>";113Pattern tagPattern→ <(\w+)>([^<]+)</\1> = Pattern.compile("<(\\w+)>([^<]+)</\\1>");114Matcher tagMatcher→ java.util.regex.Matcher[pattern=<(\w+)>([^<]+)</\1> region=0,35 lastmatch=] = tagPattern.matcher(html<div>Content</div><span>Text</span>);115116System.out.println("\nHTML content:");117while (tagMatcher.find()) {output HTML content:while (tagMatcher.find())
pass 1 of 2116System.out.println("\nHTML content:");117while (tagMatcher.find()) {118 System.out.println(" <" + tagMatcher.group(1) + ">: " + tagMatcher.group(2));119}output <div>: Contentwhile (tagMatcher.find())
pass 2 of 2116System.out.println("\nHTML content:");117while (tagMatcher.find()) {118 System.out.println(" <" + tagMatcher.group(1) + ">: " + tagMatcher.group(2));119}output <span>: Text
tweet ← Loving #java and #regex! Thanks @copilot for the help. Check out #programming tips at https://example.com Mentions: @user1 @user2 #coding
55public static void main(String[] args) {56 // Social media text57 String tweet→ Loving #java and #regex! Thanks @copilot for the help. Check out #programming tips at https://example.com Mentions: @user1 @user2 #coding = """58 Loving #java and #regex! Thanks @copilot for the help.59 Check out #programming tips at https://example.com60 Mentions: @user1 @user2 #coding61 """;6263 System.out.println("Social media extraction:");64 System.out.println("Hashtags: " + extractHashtags(tweetLoving #java and #regex! Thanks @copilot for the help. Check out #programming tips at https://example.com Mentions: @user1 @user2 #coding ));65 System.out.println("Mentions: " + extractMentions(tweet));outputSocial media extraction:hashtags ← [], pattern ← #\w+, matcher ← java.util.regex.Matcher[pattern=#\w+ region=0,138 lastmatch=]
10public static List<String> extractHashtags(String textLoving #java and #regex! Thanks @copilot for the help. Check out #programming tips at https://example.com Mentions: @user1 @user2 #coding ) {11 List<String> hashtags→ [] = new ArrayList<>();12 Pattern pattern→ #\w+ = Pattern.compile("#\\w+");13 Matcher matcher→ java.util.regex.Matcher[pattern=#\w+ region=0,138 lastmatch=] = pattern.matcher(textLoving #java and #regex! Thanks @copilot for the help. Check out #programming tips at https://example.com Mentions: @user1 @user2 #coding );return hashtags;
17 }18 return hashtags[#java, #regex, #programming, #coding];19}System.out.println("Hashtags: " + extractHashtags(tweet));
63System.out.println("Social media extraction:");64System.out.println("Hashtags: " + extractHashtags(tweetLoving #java and #regex! Thanks @copilot for the help. Check out #programming tips at https://example.com Mentions: @user1 @user2 #coding ));65System.out.println("Mentions: " + extractMentions(tweetLoving #java and #regex! Thanks @copilot for the help. Check out #programming tips at https://example.com Mentions: @user1 @user2 #coding ));outputHashtags: [#java, #regex, #programming, #coding]mentions ← [], pattern ← @\w+, matcher ← java.util.regex.Matcher[pattern=@\w+ region=0,138 lastmatch=]
21public static List<String> extractMentions(String textLoving #java and #regex! Thanks @copilot for the help. Check out #programming tips at https://example.com Mentions: @user1 @user2 #coding ) {22 List<String> mentions→ [] = new ArrayList<>();23 Pattern pattern→ @\w+ = Pattern.compile("@\\w+");24 Matcher matcher→ java.util.regex.Matcher[pattern=@\w+ region=0,138 lastmatch=] = pattern.matcher(textLoving #java and #regex! Thanks @copilot for the help. Check out #programming tips at https://example.com Mentions: @user1 @user2 #coding );return mentions;
28 }29 return mentions[@copilot, @user1, @user2];30}dataText ← Prices: $19.99, $5.50, and $100. Temperature: -5.5°C
64System.out.println("Hashtags: " + extractHashtags(tweet));65System.out.println("Mentions: " + extractMentions(tweetLoving #java and #regex! Thanks @copilot for the help. Check out #programming tips at https://example.com Mentions: @user1 @user2 #coding ));6667// Numbers68String dataText→ Prices: $19.99, $5.50, and $100. Temperature: -5.5°C = "Prices: $19.99, $5.50, and $100. Temperature: -5.5°C";69System.out.println("\nNumbers extraction:");70System.out.println("Numbers: " + extractNumbers(dataTextPrices: $19.99, $5.50, and $100. Temperature: -5.5°C));outputMentions: [@copilot, @user1, @user2] Numbers extraction:numbers ← [], pattern ← -?\d+\.?\d*, matcher ← java.util.regex.Matcher[pattern=-?\d+\.?\d* region=0,52 lastmatch=]
32public static List<Double> extractNumbers(String textPrices: $19.99, $5.50, and $100. Temperature: -5.5°C) {33 List<Double> numbers→ [] = new ArrayList<>();34 Pattern pattern→ -?\d+\.?\d* = Pattern.compile("-?\\d+\\.?\\d*");35 Matcher matcher→ java.util.regex.Matcher[pattern=-?\d+\.?\d* region=0,52 lastmatch=] = pattern.matcher(textPrices: $19.99, $5.50, and $100. Temperature: -5.5°C);return numbers;
39 }40 return numbers[19.99, 5.5, 100.0, -5.5];41}logText ← 2025-01-29: Error occurred 2025-01-30: Fixed bug 2025-02-01: Deployed
69System.out.println("\nNumbers extraction:");70System.out.println("Numbers: " + extractNumbers(dataTextPrices: $19.99, $5.50, and $100. Temperature: -5.5°C));7172// Dates73String logText→ 2025-01-29: Error occurred 2025-01-30: Fixed bug 2025-02-01: Deployed = """74 2025-01-29: Error occurred75 2025-01-30: Fixed bug76 2025-02-01: Deployed77 """;78System.out.println("\nDates extraction:");79System.out.println("Dates: " + extractDates(logText2025-01-29: Error occurred 2025-01-30: Fixed bug 2025-02-01: Deployed ));outputNumbers: [19.99, 5.5, 100.0, -5.5] Dates extraction:dates ← [], pattern ← \d{4}-\d{2}-\d{2}, matcher ← java.util.regex.Matcher[pattern=\d{4}-\d{2}-\d{2} region=0,70 lastmatch=]
43public static List<String> extractDates(String text2025-01-29: Error occurred 2025-01-30: Fixed bug 2025-02-01: Deployed ) {44 List<String> dates→ [] = new ArrayList<>();45 // YYYY-MM-DD format46 Pattern pattern→ \d{4}-\d{2}-\d{2} = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");47 Matcher matcher→ java.util.regex.Matcher[pattern=\d{4}-\d{2}-\d{2} region=0,70 lastmatch=] = pattern.matcher(text2025-01-29: Error occurred 2025-01-30: Fixed bug 2025-02-01: Deployed );return dates;
51 }52 return dates[2025-01-29, 2025-01-30, 2025-02-01];53}serverLog ← Requests from 192.168.1.1, 10.0.0.5, and 172.16.0.10
78System.out.println("\nDates extraction:");79System.out.println("Dates: " + extractDates(logText2025-01-29: Error occurred 2025-01-30: Fixed bug 2025-02-01: Deployed ));8081// IP addresses82String serverLog→ Requests from 192.168.1.1, 10.0.0.5, and 172.16.0.10 = "Requests from 192.168.1.1, 10.0.0.5, and 172.16.0.10";83Pattern ipPattern→ \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");84Matcher ipMatcher→ java.util.regex.Matcher[pattern=\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} region=0,52 lastmatch=] = ipPattern.matcher(serverLogRequests from 192.168.1.1, 10.0.0.5, and 172.16.0.10);8586System.out.println("\nIP addresses:");87while (ipMatcher.find()) {outputDates: [2025-01-29, 2025-01-30, 2025-02-01] IP addresses:while (ipMatcher.find())
pass 1 of 386System.out.println("\nIP addresses:");87while (ipMatcher.find()) {88 System.out.println(" " + ipMatcher.group());89}output 192.168.1.1quoteText ← He said "Hello" and she replied "Hi there!", quotePattern ← "([^"]+)"
91// Extract quoted strings92String quoteText→ He said "Hello" and she replied "Hi there!" = "He said \"Hello\" and she replied \"Hi there!\"";93Pattern quotePattern→ "([^"]+)" = Pattern.compile("\"([^\"]+)\"");94Matcher quoteMatcher→ java.util.regex.Matcher[pattern="([^"]+)" region=0,43 lastmatch=] = quotePattern.matcher(quoteTextHe said "Hello" and she replied "Hi there!");9596System.out.println("\nQuoted strings:");97while (quoteMatcher.find()) {output Quoted strings:while (quoteMatcher.find())
pass 1 of 296System.out.println("\nQuoted strings:");97while (quoteMatcher.find()) {98 System.out.println(" " + quoteMatcher.group(1));99}output Hellowhile (quoteMatcher.find())
pass 2 of 296System.out.println("\nQuoted strings:");97while (quoteMatcher.find()) {98 System.out.println(" " + quoteMatcher.group(1));99}output Hi there!config ← name=Ada role=admin city=London, kvPattern ← (\w+)=(\S+)
101// Key-value pairs102String config→ name=Ada role=admin city=London = "name=Ada role=admin city=London";103Pattern kvPattern→ (\w+)=(\S+) = Pattern.compile("(\\w+)=(\\S+)");104Matcher kvMatcher→ java.util.regex.Matcher[pattern=(\w+)=(\S+) region=0,31 lastmatch=] = kvPattern.matcher(configname=Ada role=admin city=London);105106System.out.println("\nKey-value pairs:");107while (kvMatcher.find()) {output Key-value pairs:while (kvMatcher.find())
pass 1 of 3106System.out.println("\nKey-value pairs:");107while (kvMatcher.find()) {108 System.out.println(" " + kvMatcher.group(1) + " = " + kvMatcher.group(2));109}output name = Adahtml ← <div>Content</div><span>Text</span>, tagPattern ← <(\w+)>([^<]+)</\1>
111// HTML tags (simple)112String html→ <div>Content</div><span>Text</span> = "<div>Content</div><span>Text</span>";113Pattern tagPattern→ <(\w+)>([^<]+)</\1> = Pattern.compile("<(\\w+)>([^<]+)</\\1>");114Matcher tagMatcher→ java.util.regex.Matcher[pattern=<(\w+)>([^<]+)</\1> region=0,35 lastmatch=] = tagPattern.matcher(html<div>Content</div><span>Text</span>);115116System.out.println("\nHTML content:");117while (tagMatcher.find()) {output HTML content:while (tagMatcher.find())
pass 1 of 2116System.out.println("\nHTML content:");117while (tagMatcher.find()) {118 System.out.println(" <" + tagMatcher.group(1) + ">: " + tagMatcher.group(2));119}output <div>: Contentwhile (tagMatcher.find())
pass 2 of 2116System.out.println("\nHTML content:");117while (tagMatcher.find()) {118 System.out.println(" <" + tagMatcher.group(1) + ">: " + tagMatcher.group(2));119}output <span>: Text
extraction
Capturing groups and repeated find calls pull pieces of information out of larger text.
Splitting Text
split uses a regex delimiter, so it can split on whitespace, punctuation, repeated separators, or a compiled pattern.
Splitting.java
Replay: real traced execution (multi-file project)
// String splitting with regex
import java.util.Arrays;
import java.util.regex.Pattern;
public class Splitting {
public static void main(String[] args) {
// Split by comma
String csv1 = "apple,banana,cherry";
String[] parts1 = csv1.split(",");
System.out.println("Split by comma:");
System.out.println(" " + Arrays.toString(parts1));
// Split by whitespace
String text1 = "one two three four";
String[] parts2 = text1.split("\\s+");
System.out.println("\nSplit by whitespace:");
System.out.println(" " + Arrays.toString(parts2));
// Split by multiple delimiters
String text2 = "apple;banana,cherry:orange";
String[] parts3 = text2.split("[;,:]+");
System.out.println("\nSplit by multiple delimiters:");
System.out.println(" " + Arrays.toString(parts3));
// Split with limit
String text3 = "one,two,three,four,five";
String[] parts4 = text3.split(",", 3);
System.out.println("\nSplit with limit (3):");
System.out.println(" " + Arrays.toString(parts4));
// Split preserving delimiters (lookahead)
String text4 = "one,two,three";
String[] parts5 = text4.split("(?=,)");
System.out.println("\nSplit preserving delimiters:");
System.out.println(" " + Arrays.toString(parts5));
// Split by word boundaries
String text5 = "hello-world_test";
String[] parts6 = text5.split("[-_]");
System.out.println("\nSplit by hyphens and underscores:");
System.out.println(" " + Arrays.toString(parts6));
// Split sentences
String paragraph = "First sentence. Second sentence! Third question?";
String[] sentences = paragraph.split("[.!?]\\s*");
System.out.println("\nSplit sentences:");
for (int i = 0; i < sentences.length; i++) {
System.out.println(" " + (i+1) + ": " + sentences[i]);
}
// Split keeping empty strings
String text6 = "a,,b,,,c";
String[] parts7 = text6.split(",");
String[] parts8 = text6.split(",", -1);
System.out.println("\nDefault (discard trailing empty):");
System.out.println(" " + Arrays.toString(parts7));
System.out.println("Keep empty strings (limit = -1):");
System.out.println(" " + Arrays.toString(parts8));
// Split path
String path = "C:\\Users\\John\\Documents\\file.txt";
String[] pathParts = path.split("\\\\");
System.out.println("\nSplit Windows path:");
System.out.println(" " + Arrays.toString(pathParts));
// Split by digits
String text7 = "abc123def456ghi";
String[] parts9 = text7.split("\\d+");
System.out.println("\nSplit by digits:");
System.out.println(" " + Arrays.toString(parts9));
// Compiled pattern for reuse
Pattern pattern = Pattern.compile("\\s*,\\s*"); // comma with optional spaces
String text8 = "a, b,c ,d , e";
String[] parts10 = pattern.split(text8);
System.out.println("\nSplit CSV with spaces:");
System.out.println(" " + Arrays.toString(parts10));
// Split complex: key=value pairs
String config = "name=John;age=30;city=NYC";
String[] pairs = config.split(";");
System.out.println("\nParse config:");
for (String pair : pairs) {
String[] kv = pair.split("=");
System.out.println(" " + kv[0] + " -> " + kv[1]);
}
}
}
// String splitting with regex
import java.util.Arrays;
import java.util.regex.Pattern;
public class Splitting {
public static void main(String[] args) {
// Split by comma
String csv1 = "red,green,blue";
String[] parts1 = csv1.split(",");
System.out.println("Split by comma:");
System.out.println(" " + Arrays.toString(parts1));
// Split by whitespace
String text1 = "one two three four";
String[] parts2 = text1.split("\\s+");
System.out.println("\nSplit by whitespace:");
System.out.println(" " + Arrays.toString(parts2));
// Split by multiple delimiters
String text2 = "apple;banana,cherry:orange";
String[] parts3 = text2.split("[;,:]+");
System.out.println("\nSplit by multiple delimiters:");
System.out.println(" " + Arrays.toString(parts3));
// Split with limit
String text3 = "one,two,three,four,five";
String[] parts4 = text3.split(",", 3);
System.out.println("\nSplit with limit (3):");
System.out.println(" " + Arrays.toString(parts4));
// Split preserving delimiters (lookahead)
String text4 = "one,two,three";
String[] parts5 = text4.split("(?=,)");
System.out.println("\nSplit preserving delimiters:");
System.out.println(" " + Arrays.toString(parts5));
// Split by word boundaries
String text5 = "hello-world_test";
String[] parts6 = text5.split("[-_]");
System.out.println("\nSplit by hyphens and underscores:");
System.out.println(" " + Arrays.toString(parts6));
// Split sentences
String paragraph = "First sentence. Second sentence! Third question?";
String[] sentences = paragraph.split("[.!?]\\s*");
System.out.println("\nSplit sentences:");
for (int i = 0; i < sentences.length; i++) {
System.out.println(" " + (i+1) + ": " + sentences[i]);
}
// Split keeping empty strings
String text6 = "a,,b,,,c";
String[] parts7 = text6.split(",");
String[] parts8 = text6.split(",", -1);
System.out.println("\nDefault (discard trailing empty):");
System.out.println(" " + Arrays.toString(parts7));
System.out.println("Keep empty strings (limit = -1):");
System.out.println(" " + Arrays.toString(parts8));
// Split path
String path = "C:\\Users\\John\\Documents\\file.txt";
String[] pathParts = path.split("\\\\");
System.out.println("\nSplit Windows path:");
System.out.println(" " + Arrays.toString(pathParts));
// Split by digits
String text7 = "abc123def456ghi";
String[] parts9 = text7.split("\\d+");
System.out.println("\nSplit by digits:");
System.out.println(" " + Arrays.toString(parts9));
// Compiled pattern for reuse
Pattern pattern = Pattern.compile("\\s*,\\s*"); // comma with optional spaces
String text8 = "a, b,c ,d , e";
String[] parts10 = pattern.split(text8);
System.out.println("\nSplit CSV with spaces:");
System.out.println(" " + Arrays.toString(parts10));
// Split complex: key=value pairs
String config = "name=John;age=30;city=NYC";
String[] pairs = config.split(";");
System.out.println("\nParse config:");
for (String pair : pairs) {
String[] kv = pair.split("=");
System.out.println(" " + kv[0] + " -> " + kv[1]);
}
}
}
csv1 ← apple,banana,cherry, text1 ← one two three four, text2 ← apple;banana,cherry:orange
8public static void main(String[] args) {9 // Split by comma10 String csv1→ apple,banana,cherry = "apple,banana,cherry"; //@csv1="apple,banana,cherry", "red,green,blue"11 String[] parts1 = csv1.split(",");12 System.out.println("Split by comma:");13 System.out.println(" " + Arrays.toString(parts1));1415 // Split by whitespace16 String text1→ one two three four = "one two three four";17 String[] parts2 = text1.split("\\s+");18 System.out.println("\nSplit by whitespace:");19 System.out.println(" " + Arrays.toString(parts2));2021 // Split by multiple delimiters22 String text2→ apple;banana,cherry:orange = "apple;banana,cherry:orange";23 String[] parts3 = text2.split("[;,:]+");24 System.out.println("\nSplit by multiple delimiters:");25 System.out.println(" " + Arrays.toString(parts3));2627 // Split with limit28 String text3→ one,two,three,four,five = "one,two,three,four,five";29 String[] parts4 = text3.split(",", 3);30 System.out.println("\nSplit with limit (3):");31 System.out.println(" " + Arrays.toString(parts4));3233 // Split preserving delimiters (lookahead)34 String text4→ one,two,three = "one,two,three";35 String[] parts5 = text4.split("(?=,)");36 System.out.println("\nSplit preserving delimiters:");37 System.out.println(" " + Arrays.toString(parts5));3839 // Split by word boundaries40 String text5→ hello-world_test = "hello-world_test";41 String[] parts6 = text5.split("[-_]");42 System.out.println("\nSplit by hyphens and underscores:");43 System.out.println(" " + Arrays.toString(parts6));4445 // Split sentences46 String paragraph→ First sentence. Second sentence! Third question? = "First sentence. Second sentence! Third question?";47 String[] sentences = paragraph.split("[.!?]\\s*");48 System.out.println("\nSplit sentences:");49 for (int i = 0; i < sentences.length; i++) {outputSplit by comma: [apple, banana, cherry] Split by whitespace: [one, two, three, four] Split by multiple delimiters: [apple, banana, cherry, orange] Split with limit (3): [one, two, three,four,five] Split preserving delimiters: [one, ,two, ,three] Split by hyphens and underscores: [hello, world, test] Split sentences:for (int i = 0; i < sentences.length; i++)
pass 1 of 348System.out.println("\nSplit sentences:");49for (int i0 = 0; i < sentences.length3; i++) {50 System.out.println(" " + (i0+1) + ": " + sentences[i]First sentence);51}output 1: First sentenceAll 3 passes — pass 1 is the card above pass isentences[i]1 0 First sentence 2 1 Second sentence 3 2 Third question text6 ← a,,b,,,c, path ← C:\Users\John\Documents\file.txt, text7 ← abc123def456ghi
53// Split keeping empty strings54String text6→ a,,b,,,c = "a,,b,,,c";55String[] parts7 = text6.split(",");56String[] parts8 = text6.split(",", -1);57System.out.println("\nDefault (discard trailing empty):");58System.out.println(" " + Arrays.toString(parts7));59System.out.println("Keep empty strings (limit = -1):");60System.out.println(" " + Arrays.toString(parts8));6162// Split path63String path→ C:\Users\John\Documents\file.txt = "C:\\Users\\John\\Documents\\file.txt";64String[] pathParts = path.split("\\\\");65System.out.println("\nSplit Windows path:");66System.out.println(" " + Arrays.toString(pathParts));6768// Split by digits69String text7→ abc123def456ghi = "abc123def456ghi";70String[] parts9 = text7.split("\\d+");71System.out.println("\nSplit by digits:");72System.out.println(" " + Arrays.toString(parts9));7374// Compiled pattern for reuse75Pattern pattern→ \s*,\s* = Pattern.compile("\\s*,\\s*"); // comma with optional spaces76String text8→ a, b,c ,d , e = "a, b,c ,d , e";77String[] parts10 = pattern.split(text8a, b,c ,d , e);78System.out.println("\nSplit CSV with spaces:");79System.out.println(" " + Arrays.toString(parts10));8081// Split complex: key=value pairs82String config→ name=John;age=30;city=NYC = "name=John;age=30;city=NYC";83String[] pairs = config.split(";");84System.out.println("\nParse config:");85for (String pair : pairs) {output Default (discard trailing empty): [a, , b, , , c] Keep empty strings (limit = -1): [a, , b, , , c] Split Windows path: [C:, Users, John, Documents, file.txt] Split by digits: [abc, def, ghi] Split CSV with spaces: [a, b, c, d, e] Parse config:for (String pair : pairs)
pass 1 of 384System.out.println("\nParse config:");85for (String pairname=John : pairs) {86 String[] kv = pair.split("=");87 System.out.println(" " + kv[0]name + " -> " + kv[1]John);88}output name -> JohnAll 3 passes — pass 1 is the card above pass pairkv[0]kv[1]1 name=John name John 2 age=30 age 30 3 city=NYC city NYC
csv1 ← red,green,blue, text1 ← one two three four, text2 ← apple;banana,cherry:orange
8public static void main(String[] args) {9 // Split by comma10 String csv1→ red,green,blue = "red,green,blue";11 String[] parts1 = csv1.split(",");12 System.out.println("Split by comma:");13 System.out.println(" " + Arrays.toString(parts1));1415 // Split by whitespace16 String text1→ one two three four = "one two three four";17 String[] parts2 = text1.split("\\s+");18 System.out.println("\nSplit by whitespace:");19 System.out.println(" " + Arrays.toString(parts2));2021 // Split by multiple delimiters22 String text2→ apple;banana,cherry:orange = "apple;banana,cherry:orange";23 String[] parts3 = text2.split("[;,:]+");24 System.out.println("\nSplit by multiple delimiters:");25 System.out.println(" " + Arrays.toString(parts3));2627 // Split with limit28 String text3→ one,two,three,four,five = "one,two,three,four,five";29 String[] parts4 = text3.split(",", 3);30 System.out.println("\nSplit with limit (3):");31 System.out.println(" " + Arrays.toString(parts4));3233 // Split preserving delimiters (lookahead)34 String text4→ one,two,three = "one,two,three";35 String[] parts5 = text4.split("(?=,)");36 System.out.println("\nSplit preserving delimiters:");37 System.out.println(" " + Arrays.toString(parts5));3839 // Split by word boundaries40 String text5→ hello-world_test = "hello-world_test";41 String[] parts6 = text5.split("[-_]");42 System.out.println("\nSplit by hyphens and underscores:");43 System.out.println(" " + Arrays.toString(parts6));4445 // Split sentences46 String paragraph→ First sentence. Second sentence! Third question? = "First sentence. Second sentence! Third question?";47 String[] sentences = paragraph.split("[.!?]\\s*");48 System.out.println("\nSplit sentences:");49 for (int i = 0; i < sentences.length; i++) {outputSplit by comma: [red, green, blue] Split by whitespace: [one, two, three, four] Split by multiple delimiters: [apple, banana, cherry, orange] Split with limit (3): [one, two, three,four,five] Split preserving delimiters: [one, ,two, ,three] Split by hyphens and underscores: [hello, world, test] Split sentences:for (int i = 0; i < sentences.length; i++)
pass 1 of 348System.out.println("\nSplit sentences:");49for (int i0 = 0; i < sentences.length3; i++) {50 System.out.println(" " + (i0+1) + ": " + sentences[i]First sentence);51}output 1: First sentenceAll 3 passes — pass 1 is the card above pass isentences[i]1 0 First sentence 2 1 Second sentence 3 2 Third question text6 ← a,,b,,,c, path ← C:\Users\John\Documents\file.txt, text7 ← abc123def456ghi
53// Split keeping empty strings54String text6→ a,,b,,,c = "a,,b,,,c";55String[] parts7 = text6.split(",");56String[] parts8 = text6.split(",", -1);57System.out.println("\nDefault (discard trailing empty):");58System.out.println(" " + Arrays.toString(parts7));59System.out.println("Keep empty strings (limit = -1):");60System.out.println(" " + Arrays.toString(parts8));6162// Split path63String path→ C:\Users\John\Documents\file.txt = "C:\\Users\\John\\Documents\\file.txt";64String[] pathParts = path.split("\\\\");65System.out.println("\nSplit Windows path:");66System.out.println(" " + Arrays.toString(pathParts));6768// Split by digits69String text7→ abc123def456ghi = "abc123def456ghi";70String[] parts9 = text7.split("\\d+");71System.out.println("\nSplit by digits:");72System.out.println(" " + Arrays.toString(parts9));7374// Compiled pattern for reuse75Pattern pattern→ \s*,\s* = Pattern.compile("\\s*,\\s*"); // comma with optional spaces76String text8→ a, b,c ,d , e = "a, b,c ,d , e";77String[] parts10 = pattern.split(text8a, b,c ,d , e);78System.out.println("\nSplit CSV with spaces:");79System.out.println(" " + Arrays.toString(parts10));8081// Split complex: key=value pairs82String config→ name=John;age=30;city=NYC = "name=John;age=30;city=NYC";83String[] pairs = config.split(";");84System.out.println("\nParse config:");85for (String pair : pairs) {output Default (discard trailing empty): [a, , b, , , c] Keep empty strings (limit = -1): [a, , b, , , c] Split Windows path: [C:, Users, John, Documents, file.txt] Split by digits: [abc, def, ghi] Split CSV with spaces: [a, b, c, d, e] Parse config:for (String pair : pairs)
pass 1 of 384System.out.println("\nParse config:");85for (String pairname=John : pairs) {86 String[] kv = pair.split("=");87 System.out.println(" " + kv[0]name + " -> " + kv[1]John);88}output name -> JohnAll 3 passes — pass 1 is the card above pass pairkv[0]kv[1]1 name=John name John 2 age=30 age 30 3 city=NYC city NYC
Replacement
replaceAll and Matcher replacement methods use regex matches to clean, mask, or reformat text.
Replacement.java
Replay: real traced execution (multi-file project)
// String replacement with regex
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Replacement {
public static void main(String[] args) {
// Simple replaceAll
String text1 = "Hello World, Hello Java";
String result1 = text1.replaceAll("Hello", "Hi");
System.out.println("Original: " + text1);
System.out.println("Replaced: " + result1);
// Replace with pattern
String text2 = "Call 555-1234 or 555-5678";
String result2 = text2.replaceAll("\\d{3}-\\d{4}", "XXX-XXXX");
System.out.println("\nMask phone numbers:");
System.out.println("Original: " + text2);
System.out.println("Masked: " + result2);
// Replace with groups
String text3 = "2025-01-29";
String result3 = text3.replaceAll("(\\d{4})-(\\d{2})-(\\d{2})", "$2/$3/$1");
System.out.println("\nReformat date:");
System.out.println("Original (YYYY-MM-DD): " + text3);
System.out.println("Reformatted (MM/DD/YYYY): " + result3);
// Remove extra whitespace
String text4 = "Too many spaces";
String result4 = text4.replaceAll("\\s+", " ");
System.out.println("\nNormalize whitespace:");
System.out.println("Original: '" + text4 + "'");
System.out.println("Normalized: '" + result4 + "'");
// Remove HTML tags
String html = "<p>Hello <b>World</b></p>";
String result5 = html.replaceAll("<[^>]+>", "");
System.out.println("\nRemove HTML:");
System.out.println("Original: " + html);
System.out.println("Clean: " + result5);
// Censor profanity (example)
String text6 = "This is bad and terrible";
String result6 = text6.replaceAll("\\b(bad|terrible)\\b", "***");
System.out.println("\nCensor words:");
System.out.println("Original: " + text6);
System.out.println("Censored: " + result6);
// Format currency
String text7 = "Price: 1234.56";
String result7 = text7.replaceAll("(\\d+)", "\\$$1");
System.out.println("\nAdd currency:");
System.out.println("Original: " + text7);
System.out.println("Formatted: " + result7);
// Matcher with appendReplacement (more control)
String text8 = "one two three";
Pattern pattern = Pattern.compile("(\\w+)");
Matcher matcher = pattern.matcher(text8);
StringBuffer result = new StringBuffer();
while (matcher.find()) {
String word = matcher.group(1);
matcher.appendReplacement(result, word.toUpperCase());
}
matcher.appendTail(result);
System.out.println("\nCustom replacement:");
System.out.println("Original: " + text8);
System.out.println("Uppercase: " + result);
// Advanced: swap first and last name
String names = "John Doe, Jane Smith, Bob Johnson";
String result9 = names.replaceAll("(\\w+)\\s(\\w+)", "$2, $1");
System.out.println("\nSwap names:");
System.out.println("Original: " + names);
System.out.println("Swapped: " + result9);
}
}
// String replacement with regex
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Replacement {
public static void main(String[] args) {
// Simple replaceAll
String text1 = "Hello World, Hello Java";
String result1 = text1.replaceAll("Hello", "Hi");
System.out.println("Original: " + text1);
System.out.println("Replaced: " + result1);
// Replace with pattern
String text2 = "Call 555-1234 or 555-5678";
String result2 = text2.replaceAll("\\d{3}-\\d{4}", "XXX-XXXX");
System.out.println("\nMask phone numbers:");
System.out.println("Original: " + text2);
System.out.println("Masked: " + result2);
// Replace with groups
String text3 = "2025-01-29";
String result3 = text3.replaceAll("(\\d{4})-(\\d{2})-(\\d{2})", "$2/$3/$1");
System.out.println("\nReformat date:");
System.out.println("Original (YYYY-MM-DD): " + text3);
System.out.println("Reformatted (MM/DD/YYYY): " + result3);
// Remove extra whitespace
String text4 = "Too many spaces";
String result4 = text4.replaceAll("\\s+", " ");
System.out.println("\nNormalize whitespace:");
System.out.println("Original: '" + text4 + "'");
System.out.println("Normalized: '" + result4 + "'");
// Remove HTML tags
String html = "<p>Hello <b>World</b></p>";
String result5 = html.replaceAll("<[^>]+>", "");
System.out.println("\nRemove HTML:");
System.out.println("Original: " + html);
System.out.println("Clean: " + result5);
// Censor profanity (example)
String text6 = "bad code can become better";
String result6 = text6.replaceAll("\\b(bad|terrible)\\b", "***");
System.out.println("\nCensor words:");
System.out.println("Original: " + text6);
System.out.println("Censored: " + result6);
// Format currency
String text7 = "Price: 1234.56";
String result7 = text7.replaceAll("(\\d+)", "\\$$1");
System.out.println("\nAdd currency:");
System.out.println("Original: " + text7);
System.out.println("Formatted: " + result7);
// Matcher with appendReplacement (more control)
String text8 = "one two three";
Pattern pattern = Pattern.compile("(\\w+)");
Matcher matcher = pattern.matcher(text8);
StringBuffer result = new StringBuffer();
while (matcher.find()) {
String word = matcher.group(1);
matcher.appendReplacement(result, word.toUpperCase());
}
matcher.appendTail(result);
System.out.println("\nCustom replacement:");
System.out.println("Original: " + text8);
System.out.println("Uppercase: " + result);
// Advanced: swap first and last name
String names = "John Doe, Jane Smith, Bob Johnson";
String result9 = names.replaceAll("(\\w+)\\s(\\w+)", "$2, $1");
System.out.println("\nSwap names:");
System.out.println("Original: " + names);
System.out.println("Swapped: " + result9);
}
}
text1 ← Hello World, Hello Java, result1 ← Hi World, Hi Java, text2 ← Call 555-1234 or 555-5678
8public static void main(String[] args) {9 // Simple replaceAll10 String text1→ Hello World, Hello Java = "Hello World, Hello Java";11 String result1→ Hi World, Hi Java = text1.replaceAll("Hello", "Hi");12 System.out.println("Original: " + text1Hello World, Hello Java);13 System.out.println("Replaced: " + result1Hi World, Hi Java);1415 // Replace with pattern16 String text2→ Call 555-1234 or 555-5678 = "Call 555-1234 or 555-5678";17 String result2→ Call XXX-XXXX or XXX-XXXX = text2.replaceAll("\\d{3}-\\d{4}", "XXX-XXXX");18 System.out.println("\nMask phone numbers:");19 System.out.println("Original: " + text2Call 555-1234 or 555-5678);20 System.out.println("Masked: " + result2Call XXX-XXXX or XXX-XXXX);2122 // Replace with groups23 String text3→ 2025-01-29 = "2025-01-29";24 String result3→ 01/29/2025 = text3.replaceAll("(\\d{4})-(\\d{2})-(\\d{2})", "$2/$3/$1");25 System.out.println("\nReformat date:");26 System.out.println("Original (YYYY-MM-DD): " + text32025-01-29);27 System.out.println("Reformatted (MM/DD/YYYY): " + result301/29/2025);2829 // Remove extra whitespace30 String text4→ Too many spaces = "Too many spaces";31 String result4→ Too many spaces = text4.replaceAll("\\s+", " ");32 System.out.println("\nNormalize whitespace:");33 System.out.println("Original: '" + text4Too many spaces + "'");34 System.out.println("Normalized: '" + result4Too many spaces + "'");3536 // Remove HTML tags37 String html→ <p>Hello <b>World</b></p> = "<p>Hello <b>World</b></p>";38 String result5→ Hello World = html.replaceAll("<[^>]+>", "");39 System.out.println("\nRemove HTML:");40 System.out.println("Original: " + html<p>Hello <b>World</b></p>);41 System.out.println("Clean: " + result5Hello World);4243 // Censor profanity (example)44 String text6→ This is bad and terrible = "This is bad and terrible"; //@text6="This is bad and terrible", "bad code can become better"45 String result6→ This is *** and *** = text6.replaceAll("\\b(bad|terrible)\\b", "***");46 System.out.println("\nCensor words:");47 System.out.println("Original: " + text6This is bad and terrible);48 System.out.println("Censored: " + result6This is *** and ***);4950 // Format currency51 String text7→ Price: 1234.56 = "Price: 1234.56";52 String result7→ Price: $1234.$56 = text7.replaceAll("(\\d+)", "\\$$1");53 System.out.println("\nAdd currency:");54 System.out.println("Original: " + text7Price: 1234.56);55 System.out.println("Formatted: " + result7Price: $1234.$56);5657 // Matcher with appendReplacement (more control)58 String text8→ one two three = "one two three";59 Pattern pattern→ (\w+) = Pattern.compile("(\\w+)");60 Matcher matcher→ java.util.regex.Matcher[pattern=(\w+) region=0,13 lastmatch=] = pattern.matcher(text8one two three);61 StringBuffer result→ (empty) = new StringBuffer();outputOriginal: Hello World, Hello Java Replaced: Hi World, Hi Java Mask phone numbers: Original: Call 555-1234 or 555-5678 Masked: Call XXX-XXXX or XXX-XXXX Reformat date: Original (YYYY-MM-DD): 2025-01-29 Reformatted (MM/DD/YYYY): 01/29/2025 Normalize whitespace: Original: 'Too many spaces' Normalized: 'Too many spaces' Remove HTML: Original: <p>Hello <b>World</b></p> Clean: Hello World Censor words: Original: This is bad and terrible Censored: This is *** and *** Add currency: Original: Price: 1234.56 Formatted: Price: $1234.$56word ← one, result ← ONE
pass 1 of 363while (matcher.find()) {64 String word→ one = matcher.group(1);65 matcher.appendReplacement(result→ ONE, word.toUpperCase());66}All 3 passes — pass 1 is the card above pass wordresult1 one (empty) → ONE 2 two ONE → ONE TWO 3 three ONE TWO → ONE TWO THREE names ← John Doe, Jane Smith, Bob Johnson, result9 ← Doe, John, Smith, Jane, Johnson, Bob
66 }67 matcher.appendTail(resultONE TWO THREE);6869 System.out.println("\nCustom replacement:");70 System.out.println("Original: " + text8one two three);71 System.out.println("Uppercase: " + resultONE TWO THREE);7273 // Advanced: swap first and last name74 String names→ John Doe, Jane Smith, Bob Johnson = "John Doe, Jane Smith, Bob Johnson";75 String result9→ Doe, John, Smith, Jane, Johnson, Bob = names.replaceAll("(\\w+)\\s(\\w+)", "$2, $1");76 System.out.println("\nSwap names:");77 System.out.println("Original: " + namesJohn Doe, Jane Smith, Bob Johnson);78 System.out.println("Swapped: " + result9Doe, John, Smith, Jane, Johnson, Bob);79}output Custom replacement: Original: one two three Uppercase: ONE TWO THREE Swap names: Original: John Doe, Jane Smith, Bob Johnson Swapped: Doe, John, Smith, Jane, Johnson, Bob
text1 ← Hello World, Hello Java, result1 ← Hi World, Hi Java, text2 ← Call 555-1234 or 555-5678
8public static void main(String[] args) {9 // Simple replaceAll10 String text1→ Hello World, Hello Java = "Hello World, Hello Java";11 String result1→ Hi World, Hi Java = text1.replaceAll("Hello", "Hi");12 System.out.println("Original: " + text1Hello World, Hello Java);13 System.out.println("Replaced: " + result1Hi World, Hi Java);1415 // Replace with pattern16 String text2→ Call 555-1234 or 555-5678 = "Call 555-1234 or 555-5678";17 String result2→ Call XXX-XXXX or XXX-XXXX = text2.replaceAll("\\d{3}-\\d{4}", "XXX-XXXX");18 System.out.println("\nMask phone numbers:");19 System.out.println("Original: " + text2Call 555-1234 or 555-5678);20 System.out.println("Masked: " + result2Call XXX-XXXX or XXX-XXXX);2122 // Replace with groups23 String text3→ 2025-01-29 = "2025-01-29";24 String result3→ 01/29/2025 = text3.replaceAll("(\\d{4})-(\\d{2})-(\\d{2})", "$2/$3/$1");25 System.out.println("\nReformat date:");26 System.out.println("Original (YYYY-MM-DD): " + text32025-01-29);27 System.out.println("Reformatted (MM/DD/YYYY): " + result301/29/2025);2829 // Remove extra whitespace30 String text4→ Too many spaces = "Too many spaces";31 String result4→ Too many spaces = text4.replaceAll("\\s+", " ");32 System.out.println("\nNormalize whitespace:");33 System.out.println("Original: '" + text4Too many spaces + "'");34 System.out.println("Normalized: '" + result4Too many spaces + "'");3536 // Remove HTML tags37 String html→ <p>Hello <b>World</b></p> = "<p>Hello <b>World</b></p>";38 String result5→ Hello World = html.replaceAll("<[^>]+>", "");39 System.out.println("\nRemove HTML:");40 System.out.println("Original: " + html<p>Hello <b>World</b></p>);41 System.out.println("Clean: " + result5Hello World);4243 // Censor profanity (example)44 String text6→ bad code can become better = "bad code can become better";45 String result6→ *** code can become better = text6.replaceAll("\\b(bad|terrible)\\b", "***");46 System.out.println("\nCensor words:");47 System.out.println("Original: " + text6bad code can become better);48 System.out.println("Censored: " + result6*** code can become better);4950 // Format currency51 String text7→ Price: 1234.56 = "Price: 1234.56";52 String result7→ Price: $1234.$56 = text7.replaceAll("(\\d+)", "\\$$1");53 System.out.println("\nAdd currency:");54 System.out.println("Original: " + text7Price: 1234.56);55 System.out.println("Formatted: " + result7Price: $1234.$56);5657 // Matcher with appendReplacement (more control)58 String text8→ one two three = "one two three";59 Pattern pattern→ (\w+) = Pattern.compile("(\\w+)");60 Matcher matcher→ java.util.regex.Matcher[pattern=(\w+) region=0,13 lastmatch=] = pattern.matcher(text8one two three);61 StringBuffer result→ (empty) = new StringBuffer();outputOriginal: Hello World, Hello Java Replaced: Hi World, Hi Java Mask phone numbers: Original: Call 555-1234 or 555-5678 Masked: Call XXX-XXXX or XXX-XXXX Reformat date: Original (YYYY-MM-DD): 2025-01-29 Reformatted (MM/DD/YYYY): 01/29/2025 Normalize whitespace: Original: 'Too many spaces' Normalized: 'Too many spaces' Remove HTML: Original: <p>Hello <b>World</b></p> Clean: Hello World Censor words: Original: bad code can become better Censored: *** code can become better Add currency: Original: Price: 1234.56 Formatted: Price: $1234.$56word ← one, result ← ONE
pass 1 of 363while (matcher.find()) {64 String word→ one = matcher.group(1);65 matcher.appendReplacement(result→ ONE, word.toUpperCase());66}All 3 passes — pass 1 is the card above pass wordresult1 one (empty) → ONE 2 two ONE → ONE TWO 3 three ONE TWO → ONE TWO THREE names ← John Doe, Jane Smith, Bob Johnson, result9 ← Doe, John, Smith, Jane, Johnson, Bob
66 }67 matcher.appendTail(resultONE TWO THREE);6869 System.out.println("\nCustom replacement:");70 System.out.println("Original: " + text8one two three);71 System.out.println("Uppercase: " + resultONE TWO THREE);7273 // Advanced: swap first and last name74 String names→ John Doe, Jane Smith, Bob Johnson = "John Doe, Jane Smith, Bob Johnson";75 String result9→ Doe, John, Smith, Jane, Johnson, Bob = names.replaceAll("(\\w+)\\s(\\w+)", "$2, $1");76 System.out.println("\nSwap names:");77 System.out.println("Original: " + namesJohn Doe, Jane Smith, Bob Johnson);78 System.out.println("Swapped: " + result9Doe, John, Smith, Jane, Johnson, Bob);79}output Custom replacement: Original: one two three Uppercase: ONE TWO THREE Swap names: Original: John Doe, Jane Smith, Bob Johnson Swapped: Doe, John, Smith, Jane, Johnson, Bob
Exercise: Practical.java
Extract all hashtags and mentions from a social media post and return them as separate lists