Open In App

Java Regex Programs – Basic to Advanced

Last Updated : 17 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, Regular Expressions or Regex (in short) in Java is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Regular Expressions in Java are provided under java.util.regex package. This consists of 3 classes and 1 interface.

In Java Interviews, Regex questions are generally asked by Interviewer So, it’s necessary to practice these questions in order to succeed in the Interview.

This article provides a variety of programs on Java Regex, that are frequently asked in the technical round in various Software Engineering/JAVA Backend Developer Interviews. Additionally, All practice programs come with a detailed description, Java code, and output.

Java Regular Expression Programs for Practice: Complete List

  1. How to reset the pattern of a regular expression?
  2. Remove duplicate words from Sentences using Regular Expression
  3. How to find every occurrence of a word?
  4. How to know the last index of a particular word in a string?
  5. Java Program to Print all the Strings that Match a Given Pattern from a File
  6. How to remove the white spaces?
  7. How to match phone numbers in a list to a certain pattern?
  8. How to count a group of words in a string?
  9. How to search a particular word in a string?
  10. Split() String method in Java with examples
  11. How to count replace the first occurrence of a String?
  12. How to check whether the date is in the proper format or not?
  13. Check if the Email Address is Valid or not in Java
  14. How to replace all occurings of a string?
  15. How to make the first character of each word in Uppercase?
  16. Write a program to check whether the given character string is starting with vowel or not ?
  17. write a program to check whether the given variable name is valid according to the naming convention or not ?
  18. Write a program to split the string based on the given regular expression?

Conclusion

In Conclusion, By practising these Java Regular Expression questions you will get enough confidence to face any Java regex questions in your upcoming Interview. 

Also, feel free to check out our Java interview questions collection – it could come in handy!

Java Programs for Regular Expression – FAQs

1. Write a program to validate a email address?

Java




import java.util.regex.*;
 
public class ValidateEmail {
 
    public static void main(String[] args)
    {
        String email = "hello_World@geeksforgeeks.org";
        String regex
            = "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z]{2,6}$";
 
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(email);
 
        boolean isEmailValid = matcher.matches();
 
        if (isEmailValid) {
            System.out.println("Email is valid");
        }
        else {
            System.out.println("Email is invalid");
        }
    }
}


Output

Email is valid

2. Write a Program to validate a phone number?

Java




import java.util.regex.*;
 
public class ValidatePhone {
 
    public static void main(String[] args)
    {
        String phone = "123-456-7890";
        String regex = "^\\d{3}-\\d{3}-\\d{4}$";
 
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(phone);
 
        boolean isPhoneValid = matcher.matches();
 
        if (isPhoneValid) {
            System.out.println("Phone number is valid");
        }
        else {
            System.out.println("Phone number is invalid");
        }
    }
}


Output

Phone number is valid

3. Write a program Extract a URL from String?

Java




import java.util.regex.*;
 
public class ExtractURL {
 
    public static void main(String[] args) {
        String text = "This is a website: https://www.geeksforgeeks.org";
        String regex = "https?://[\\w\\.\\-]+\\.[a-z]{2,6}";
 
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);
 
        while (matcher.find()) {
            String url = matcher.group();
            System.out.println("URL found: " + url);
        }
    }
}


Output

URL found: https://www.geeksforgeeks.org

4. Write a program to replace all the spaces with “_” underscore in a String?

Java




import java.util.regex.*;
 
public class ReplaceSpaces {
 
    public static void main(String[] args) {
        String text = "geeks for geeks";
        String regex = "\\s";
        String replacement = "_";
 
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);
 
        String newText = matcher.replaceAll(replacement);
        System.out.println("New text: " + newText);
    }
}


Output

New text: geeks_for_geeks

5. Write a program to check whether the given character string is starting with vowel ?

Java




import java.util.regex.*;
class GFG {
    public static void main(String args[])
    {
        String arr[] = new String[4];
        
        arr[0] = "Elephant";
          
        arr[1] = "animal";
          
        arr[2] = "geeks";
       
        arr[3] = "i";
         
      for(String str : arr)
      {
         /*It matches all the words that starts with vowels followed by zero or
         more alphabets even it is a single character
         */
        if (Pattern.matches("^[AEIOUaeiou][A-Za-z]*",
                            str)) {
            System.out.println(str + " is accepted");
        }
        else {
            System.out.println(str + " is not accepted");
        }
      }
    }
}


Output

Elephant is accepted
animal is accepted
geeks is not accepted
i is accepted

6. Write a program to check whether the given variable name is valid according to the naming convention or not ?

Java




import java.util.regex.*;
class GFG {
    public static void main(String args[])
    {
        String str[] = new String[4];
 
        str[0] = "_Geeks9";
 
        str[1] = "$Geeks20203";
 
        str[2] = "9for_y";
 
        str[3] = "Geeks_For_Geeks";
        //Here we have compiled the regex and assigned it to a pattern object
        Pattern p
            = Pattern.compile("^[_$a-zA-Z][a-zA-Z0-9_$]*$");
      /*The regex tells whether the given variable is valid or not according
         to the naming conventions of the variable.
                                                     */
 
        for (String i : str) {
            Matcher m = p.matcher(i);
            //Now we are matching the string with the compiled string
            String string = "";
 
            while (m.find())
 
            {
                string += m.group();
            }
 
            // If the string is matched then it will not be an empty string
            if (!string.equals("")) {
                System.out.println(
                    string + " is  a valid variable name");
            }
        }
    }
}


Output

_Geeks9 is  a valid variable name
$Geeks20203 is  a valid variable name
Geeks_For_Geeks is  a valid variable name

The split() function takes a regular expression as parameter and it splits the string based on the given regular expression. In general we use the split function that is present in the String class which splits the string based on the regular expression.

Java




class gfg  {
     
    public static void main(String args[])
    {
        String str = "charitha@gmail.com";
          
        String regex = "@";
         
        String arr[] = str.split(regex);
         
        System.out.println("User name : "+arr[0]);
         
        System.out.println("Domain name : "+arr[1]);
    }
     
     
}


Output

User name : charitha
Domain name : gmail.com


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads