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.3K+ Learners
    4.37  (87)
    Greedy Algorithm
    2 hrs
    Beginner
    2.7K+ Learners
    4.53  (338)
    Tower of Hanoi
    1 hrs
    Beginner
    889 Learners
    4.67  (36)
    Prims Algorithm
    1 hrs
    Beginner
    928 Learners
    4.34  (62)
    Digital Clock in Python
    1 hrs
    Beginner
    2.1K+ Learners
    4.46  (100)
    KMP Algorithm
    2 hrs
    Beginner
    764 Learners
    4.58  (19)
    Electric Vehicle Design
    1 hrs
    Beginner
    9.7K+ Learners
    4.48  (579)