Top Java Regex(2023) Interview Questions | CodeUsingJava
















Top Java Regex Interview Questions


  1. What are Java Regex?
  2. What are the type of classes in Java?
  3. What is Matcher class?
  4. What is an example of Java Regular Expressions?
  5. Write a regex to split String by new line?
  6. How can we split Java String by newlines?
  7. What is a metacharacter?
  8. What is Flags?
  9. What is Capturing Groups?
  10. Give a program for demonstrate simple pattern searching?
  11. How to validate an email address in JavaScript?
  12. How to negate specific word in regex?
  13. How to count string occurrence in string?
  14. How can we replace multiple spaces with a single space?

What are Java Regex?

Java Regex is a string pattern whic is used in searching, manipulating and editing a string in Java.It is an API for defining a pattern for the constraint on string like password and email validation, it is able for testing our regular expression by the Java Regex Tool.Regex is mainly provided under Java.

Regex

What are the type of classes in Java?

There are three types of classes in Java:
  • Pattern Class - Used as a compiled representation of a regular expression.It provides no public constructors.
  • Matcher Class - Used as an engine which interprets the pattern and also performs match operations against an input string.
  • PatternSyntaxException - Used in indicating a syntax error in a regular expression pattern.

What is Matcher class?

Matcher Class helps in performing match operations on a character sequence.The method description is as follows:
boolean matches() used in testing the regular expression which matches the pattern.
boolean find() helps in finding the next expression which matcges the pattern.
boolean find(int start) used in finding the next expression which matches the pattern from given the start number.
String group() helps in returning the matched subsequence.
int start() helps in returning the starting index of the matched subsequence.
int end() helps in returning the ending index of the matched subsequence.
int groupCount() helps in returning the total number of the matched subsequence.

What is an example of Java Regular Expressions?

Here is an example of Java Regular Expression:
import java.util.regex.*;  
public class RegexExample1{  
public static void main(String args[]){  
//1st way  
Pattern p = Pattern.compile(".s");//. represents single character  
Matcher m = p.matcher("as");  
boolean b = m.matches();  
 
//2nd way  
boolean b2=Pattern.compile(".s").matcher("as").matches();  
 
//3rd way  
boolean b3 = Pattern.matches(".s", "as");  
 
System.out.println(b+" "+b2+" "+b3);  
}}  


Write a regex to split String by new line?

String lines[] = string.split("\\r?\\n");


How can we split Java String by newlines?

There are many ways for entering a new line character:
\r represents CR (Carriage Return), which is used in Unix
\n means LF (Line Feed), used in Mac OS
\r\n means CR + LF, used in Windows

The most forward way for splitting strings by new line is :
String lines[] = String.split("\\r?\\n");


What is a metacharacter?

Metacharacter acts as a special meaning to a regular expression engine.It is not counted as a regular character by the regex engine.

What is Flags?

Flags in java are the method for changing the search when it is performed.Here are some of the options of flag:
Pattern.CASE_INSENSITIVE - The case of letters will be ignored when performing a search.
Pattern.LITERAL - Special characters in the pattern will not have any special meaning and will be treated as ordinary characters when performing a search.
Pattern.UNICODE_CASE - Use it together with the CASE_INSENSITIVE flag to also ignore the case of letters outside of the English alphabet.

What is Capturing Groups?

Capturing Groups are used for treating multiple characters as a single unit, it is created by placing the characters to be grouped inside a set of parentheses.
There are 4 types of such groups:
((A)(B(C)))
(A)
(B(C))
(C)

Give a program for demonstrate simple pattern searching?


// A Simple Java program to demonstrate working of
// String matching in Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
class Demo
{
    public static void main(String args[])
    {
        // Create a pattern to be searched
        Pattern pattern = Pattern.compile("geeks");
 
        // Search above pattern in "geeksforgeeks.org"
        Matcher m = pattern.matcher("geeksforgeeks.org");
 
        // Print starting and ending indexes of the pattern
        // in text
        while (m.find())
            System.out.println("Pattern found from " + m.start() +
                               " to " + (m.end()-1));
    }
}

OUTPUT:
Pattern found from 0 to 4
Pattern found from 8 to 12



How to validate an email address in JavaScript?

Here is an example for validating an email address in JavaScript:

function validateEmail(email) {
  const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(email);
}

function validate() {
  const $result = $("#result");
  const email = $("#email").val();
  $result.text("");

  if (validateEmail(email)) {
    $result.text(email + " is valid :)");
    $result.css("color", "green");
  } else {
    $result.text(email + " is not valid :(");
    $result.css("color", "red");
  }
  return false;
}

$("#validate").on("click", validate);



How to negate specific word in regex?

We can negate word in regex by using the following code:
^(?!.*bar).*$

The negative lookahead construct is the pair of parentheses.

How to count string occurrence in string?

var temp = "This is a string.";
var count = (temp.match(/is/g) || []).length;
console.log(count);


How can we replace multiple spaces with a single space?

We can cover tabs, newlines by using the following code:
string = string.replace(/\s\s+/g, ' ');

We can cover only spaces by using the following code:
string = string.replace(/  +/g, ' ');