Java - Regular Expressions Part 5: Maps vs Objects

1. Validating Emails

String pattern = "^[\\w.-]+@[\\w.-]+\\.\\w+$";

System.out.println("Valid Email: " + "[email protected]".matches(pattern)); // true

System.out.println("Valid Email: " + "[email protected]".matches(pattern));       // false

2. Splitting Strings

String text = "apple,banana,orange";

String[] fruits = text.split(",");

for (String fruit : fruits) {

    System.out.println(fruit);

}

// apple

// banana

// orange

3. Replacing Text

String text = "I like Java.";

String result = text.replaceAll("Java", "Python");

System.out.println(result); // I like Python.

4. Extracting Numbers

Pattern pattern = Pattern.compile("\\d+");

Matcher matcher = pattern.matcher("Item: 123, Price: 456");

while (matcher.find()) {

    System.out.println("Number: " + matcher.group());

}

// Number: 123

// Number: 456

Conclusion

This expanded guide provides a thorough breakdown of Java Regex concepts, complete with examples for each use case. By mastering these features, you can handle text-processing tasks efficiently in Java.