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

    Convert Video to GIF in Python
    1 hrs
    Beginner
    2.2K+ Learners
    4.36  (59)
    Basics of Graph Theory
    2 hrs
    Beginner
    1.5K+ Learners
    4.61  (61)
    Lambda Expression in Java
    1 hrs
    Intermediate
    2K+ Learners
    4.53  (68)
    Greedy Algorithm
    2 hrs
    Beginner
    1.9K+ Learners
    4.56  (87)
    Tower of Hanoi
    1 hrs
    Beginner
    790 Learners
    4.74  (27)
    Prims Algorithm
    1 hrs
    Beginner
    783 Learners
    4.64  (36)
    Digital Clock in Python
    1 hrs
    Beginner
    1.9K+ Learners
    4.48  (82)
    KMP Algorithm
    2 hrs
    Beginner
    693 Learners
    4.6  (15)
    Electric Vehicle Design
    1 hrs
    Beginner
    9.3K+ Learners
    4.52  (447)
    Great Learning Career Kickstarter Test - Software Development
    1 hrs
    Beginner
    469 Learners
    4.0  (4)