Java

Regular Expressions

Regular Expressions

Java's regular expression capabilities are among its most powerful features, providing developers with a versatile and robust way for text manipulation. Regular expressions allow users to create complex patterns which can be used to search for matches within strings; extract substrings; replace characters or entire words based on predefined rules – making them ideal when dealing with complex data processing tasks! Furthermore, Java provides several helpful methods related to regex operations such as compile() enabling the definition of new patterns in memory; matcher() allowing string input to be compared against a given pattern; finally split() method dividing strings into multiple components - all helping make complex tasks simpler while increasing performance significantly during runtime execution. 

Examples of RegEx: 
1. Validating an email address: 

String pattern = 
"^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$"; Pattern p = Pattern.compile(pattern); 
Matcher m = p.matcher("example@email.com"); 
if (m.matches()) { 
System.out.println("valid email address"); 
} else { 
System.out.println("invalid email address"); 
} 

2. Extracting all phone numbers from a string 

String pattern = "\\d{3}-\\d{3}-\\d{4}"; 
Pattern p = Pattern.compile(pattern); 
Matcher m = p.matcher("My phone number is 555-555-5555 and my office number is 444-444-4444"); 
while (m.find()) { 
System.out.println(m.group()); 
} 

Output : 

555-555-5555 
444-444-4444 

3. Extracting all URLs from a string: 

String pattern = "(https?|ftp|file):/ [-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; Pattern p = Pattern.compile(pattern); 
Matcher m = p.matcher("My website is http:/ www.example.com and my blog is https:/ blog.example.com"); 
while (m.find()) { 
System.out.println(m.group()); 
} 

Output: 

http://www.example.com 
https://blog.example.com 


 

Top course recommendations for you

    Lambda Expression in Java
    1 hrs
    Intermediate
    2.4K+ Learners
    4.39  (98)
    Greedy Algorithm
    2 hrs
    Beginner
    3K+ Learners
    4.54  (581)
    Tower of Hanoi
    1 hrs
    Beginner
    920 Learners
    4.69  (42)
    Prims Algorithm
    1 hrs
    Beginner
    1K+ Learners
    4.41  (91)
    Digital Clock in Python
    1 hrs
    Beginner
    2.2K+ Learners
    4.49  (109)
    KMP Algorithm
    2 hrs
    Beginner
    792 Learners
    4.71  (28)
    Electric Vehicle Design
    1 hrs
    Beginner
    9.8K+ Learners
    4.48  (597)