DEV Community

Tamilselvan K
Tamilselvan K

Posted on

Day-79 Understanding Regular Expressions in Java

What is a Regular Expression?

A regular expression is a sequence of characters that defines a search pattern. When you need to find specific data in a text or perform complex text manipulations, regex can help you achieve it efficiently.

Key uses of regex in Java:

  • Performing all types of text search operations.
  • Replacing text based on defined patterns.

Core Classes in Java Regex

  1. Pattern Class
    Defines a compiled version of a regex pattern, which can be used for matching operations.

  2. Matcher Class
    Used to search for occurrences of a pattern in a given text.

  3. PatternSyntaxException Class
    Indicates a syntax error in the regex pattern.

Example Use Cases:

  • Chatbot applications
  • Form validation
  • Compiler and interpreter development

Example Java Code

package filedemo;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexDemo {
    public static void main(String[] args) {
        String Line = "Tamil Tamilnadu Tamilan";
        Pattern p = Pattern.compile("Tamil");
        Matcher m = p.matcher(Line);
        while(m.find())
        {
            System.out.println(m.group());
        }

    }
}

Enter fullscreen mode Exit fullscreen mode

Common Regex Syntax in Java

Special Characters

  • [a-z] – Matches one character from a to z.
  • [^abc] – Matches any character except a, b, or c.
  • [0-9] – Matches one digit from 0 to 9.

Metacharacters

  • ^ – Matches the beginning of a string.
  • $ – Matches the end of a string.
  • \s – Matches a whitespace character.
  • \S – Matches a non-whitespace character.
  • \d – Matches a digit.
  • \D – Matches a non-digit.
  • \w – Matches a word character (letters, digits, underscore).
  • \W – Matches a non-word character (including spaces and symbols).
  • \b – Matches a word boundary.
  • | – Alternation (OR) operator, matches one pattern or another.
  • . – Matches any single character (except newline).

Quantifiers

  • a+ – Matches one or more occurrences of "a".
  • a* – Matches zero or more occurrences of "a".
  • a? – Matches zero or one occurrence of "a".
  • a{2} – Matches exactly two occurrences of "a".
  • a{1,3} – Matches between one and three occurrences of "a".

Mobile Number Pattern Example

String mobilePattern = "(0|91)?[6-9][0-9]{9}";
Enter fullscreen mode Exit fullscreen mode

This pattern:

  • Allows an optional "0" or "91" country code.
  • Ensures the number starts with digits 6–9.
  • Ensures exactly 10 digits follow.

Top comments (0)