Java Regex Programs – Basic to Advanced
Last Updated :
17 Nov, 2023
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
- How to reset the pattern of a regular expression?
- Remove duplicate words from Sentences using Regular Expression
- How to find every occurrence of a word?
- How to know the last index of a particular word in a string?
- Java Program to Print all the Strings that Match a Given Pattern from a File
- How to remove the white spaces?
- How to match phone numbers in a list to a certain pattern?
- How to count a group of words in a string?
- How to search a particular word in a string?
- Split() String method in Java with examples
- How to count replace the first occurrence of a String?
- How to check whether the date is in the proper format or not?
- Check if the Email Address is Valid or not in Java
- How to replace all occurings of a string?
- How to make the first character of each word in Uppercase?
- Write a program to check whether the given character string is starting with vowel or not ?
- write a program to check whether the given variable name is valid according to the naming convention or not ?
- 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" );
}
}
}
|
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 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)
{
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" ;
Pattern p
= Pattern.compile( "^[_$a-zA-Z][a-zA-Z0-9_$]*$" );
for (String i : str) {
Matcher m = p.matcher(i);
String string = "" ;
while (m.find())
{
string += m.group();
}
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
Share your thoughts in the comments
Please Login to comment...