In this short tutorial, we are going to explain how to use the regex wildcard to match characters.

First, we will start with a little bit of background on what wildcard means in regular expressions.

Then, we are going to showcase how to use it using practical examples.

What is Wildcard

A wildcard is a generic term describing something that can represent anything. For example, a joker is simply a wildcard in poker.

In regular expressions, a wildcard is a symbol that can be used to represent characters in a given string.

For instance, the dot sign ”.” is the wildcard that denotes any single character in a regex.

Wildcard / Quantifiers Description
. wildcard represents any character except newline
* quantifier that matches zero or more times
+ quantifier that matches one or more times
? quantifier that matches zero or one time

As we can see, quantifiers indicate how many characters must be present in the string for a match to be found.

Wildcard in Regular Expression

As we explained earlier, the idea of a wildcard is to replace any character so that we can use regular expressions with ease.

Now, let’s see how we can use the wildcard with quantifiers and anchors in practical regex examples:

^dev.*us$ matches a string that starts with the word "dev", followed by zero or many characters and ends with the word "us"
[0-9].?$ matches any string that ends with a number
^[a-z].+ macthes a string that starts with a lowercase letter, followed by one or more characters
.\*\\d$ macthes any string that contains zero or more characters and ends with a digit

Please bear in mind that the caret “^” will negate the specified class if it’s used inside brackets. For example, [^0-9] means NOT a digit.

Next, we are going to compile the above regular expressions against strings in Java:

    
        public static void main(String[] args) {
            Pattern.compile("^dev.*us$")
                .matcher("devwithus")
                .find(); // true

            Pattern.compile("[0-9].?$")
                .matcher("2023Y")
                .find(); // true
                
            Pattern.compile("[0-9].?$")
                .matcher("2023 now")
                .find(); // false

            Pattern.compile("^[a-z].+")
                .matcher("hello")
                .find(); // true
                
            Pattern.compile(".*\\d$")
                .matcher("hello 2013")
                .find(); // true
        }
    

Another important rule to keep in mind is that if we want to match the dot itself, we need to use the backslash “\.” to escape it.

    
        public static void main(String[] args) {
            Pattern.compile("\\.$")
                .matcher("this is a dot .")
                .find(); // true
        }
    

Conclusion

In this short article, we have explained in detail what the wildcard ”.” means in regex.

Along the way, we showcased how to use it in regular expressions using practical examples.