Matches any single character except a newline (.)

1. Match Any Single Character Using .

This program demonstrates the dot (.) metacharacter in Java regular expressions. The . matches any single character except a newline. It finds and displays each character matched by the pattern.

import java.util.regex.*;

public class DotCharacterMatch {
    public static void main(String[] args) {
        String input = "Hello";
        Pattern pattern = Pattern.compile(".");
        Matcher matcher = pattern.matcher(input);

        while (matcher.find()) {
            System.out.println("Matched: " + matcher.group());
        }
    }
}
Output:
Matched: H
Matched: e
Matched: l
Matched: l
Matched: o

2. Match Characters in a Sentence Using .

This program uses . to match every character in a sentence except a newline. The pattern treats letters, spaces, and numbers as individual characters. Each matched character is displayed separately.

import java.util.regex.*;

public class DotWithSentence {
    public static void main(String[] args) {
        String input = "Java 123";
        Pattern pattern = Pattern.compile(".");
        Matcher matcher = pattern.matcher(input);

        while (matcher.find()) {
            System.out.println("Matched: " + matcher.group());
        }
    }
}
Output:
Matched: J
Matched: a
Matched: v
Matched: a
Matched:  
Matched: 1
Matched: 2
Matched: 3
Scroll to Top