Search Tutorials


Top Java Regular Expression(Regex) Interview Questions | JavaInUse



Top Java Regular Expression(Regex)frequently asked interview questions.

In this post we will look at Java Regular Expression(Regex) Interview questions. Examples are provided with explanations.


Q: What are Java Regex ?
A:
Java provides the java.util.regex package for pattern matching with regular expressions.
It is widely used to define the constraint on strings such as password and email validation.
The java.util.regex package provides following classes and interfaces for regular expressions.
  • MatchResult interface
  • Matcher class
  • Pattern class
  • PatternSyntaxException class
Q: Write a regex to split String by new line?
A:
String lines[] = string.split("\\r?\\n");


Q: What is use of Dot(.) symbol in Java Regex?
A:
The dot is used for matching any character. For example, the following regex represents "a number plus any other character":
[0-9].


Q: How to extract a substring using regex ?
Example - String test = "This is a test String and 'This is data we want'"
A:
String data = "This is a test String and 'This is data we want'";
Pattern pattern = Pattern.compile("'(.*?)'");
Matcher matcher = pattern.matcher(data);
if (matcher.find())
{
    System.out.println(matcher.group(1));
}


Q: What are the different repetition operators in Java Regex?
A:
Regex Operator Functionality Example
* Zero or more occurrences . * - Any sequence
? Zero or one occurrences(Optional) [0-9]? - Any optional digit
+ One or more occurrences [0-9]+ - One or more digit
{x} x instance of occurrences m{5} - Five instances of the letter m
{x,y} between x and y instances of occurrences [0-9]{13,19} - Between 13 and 19 digits
{x,} at least x instances of occurrences .{8,} - At least 8 characters

Q: What is difference between matches() and find() in Java Regex?
A:
matches() returns true only if the whole string matches the specified pattern while find() returns trues even if a substring matches the pattern.
import java.util.regex.*;

public class RegexTutorial {
	public static void main(String[] args) {
        Pattern pattern = Pattern.compile("\\d");
        String test = "JavaInUse123";
        Matcher m = pattern.matcher(test);

        if (m != null){
            System.out.println(m.find());
            System.out.println(m.matches());
        }
    }
}


Q: How to replace all non-alphanumeric characters with empty strings?
A:
replaceAll("[^A-Za-z0-9]", "");


Q: How to replace 2 or more spaces with single space in string and delete leading and trailing spaces?

Example - String test = " Test String " should be returned as "Test String"
A:
replaceAll("\\s{2,}", " ").trim();


Q: Create a regular expression that accepts alphanumeric characters only. Its length must be five characters long only
A:
import java.util.regex.*;

public class RegexTutorial {
	public static void main(String args[]) {
		System.out.println(Pattern.matches("[a-zA-Z0-9]{5}", "java1"));
		System.out.println(Pattern.matches("[a-zA-Z0-9]{5}", "java12"));
		System.out.println(Pattern.matches("[a-zA-Z0-9]{5}", "JA1Va"));
		System.out.println(Pattern.matches("[a-zA-Z0-9]{5}", "Java$"));
	}
}  


Q: Create a regular expression that accepts 10 digit numeric characters starting with 1, 2 or 3 only.
A:
import java.util.regex.*;

public class RegexTutorial{

	public static void main(String args[]) {
		System.out.println("Regex Using character classes and quantifiers");

		System.out.println(Pattern.matches("[123]{1}[0-9]{9}", "1953038949"));
		System.out.println(Pattern.matches("[123][0-9]{9}", "1993038949"));

		System.out.println(Pattern.matches("[123][0-9]{9}", "9950389490"));
		System.out.println(Pattern.matches("[123][0-9]{9}", "695338949"));
		System.out.println(Pattern.matches("[123][0-9]{9}", "885338949"));

		System.out.println("Regex Using Metacharacters");
		System.out.println(Pattern.matches("[123]{1}\\d{9}", "2885338949"));
		System.out.println(Pattern.matches("[123]{1}\\d{9}", "685308949"));

	}
}


See Also

Spring Boot Interview Questions Apache Camel Interview Questions Drools Interview Questions Java 8 Interview Questions Enterprise Service Bus- ESB Interview Questions. JBoss Fuse Interview Questions Angular 2 Interview Questions