Regex Wildcard Character – A Complete Guide

What is the wildcard character in regex?

In regular expressions, a wildcard character is represented by a period “.” and will match any character. They are often combined with quantifiers, for example, the zero-or-more quantifier * to match a string of any character length or a specific quantifier (e.g. {5}) to match a string of a specific length.

/./Edit with Regexity

How Does it Work?

The wildcard character matches any character. For example, the following expression will match benEdit with Regexity, banEdit with Regexity, bunEdit with Regexity, binEdit with Regexity, and any other string with the letter bEdit with Regexity at the start, nEdit with Regexity at the end, and a character in between.

/b.n/Edit with Regexity

You can combine it with a quantifier for even more options. For example, the following expression will match beanEdit with Regexity, beenEdit with Regexity, brownEdit with Regexity, etc.

/b.+n/Edit with Regexity

It does not only match letters, though. It will also match digits, spaces, and special characters. So the first expression above will also match:

Where Can You Use the Wildcard Character

The regex wildcard character can be used wherever you’d like to match any character. As the name implies, it is a wildcard and therefore has very few limitations.

The only exception to this rule is when the period is used inside a character class such as [p.p]Edit with Regexity. In this case, the period is matched literally, even though other character sets such as \dEdit with Regexity or \sEdit with Regexity have their original meaning. Therefore, any of the characters inside the character class, including the period, will be matched. For example, the following expression will match only b.nEdit with Regexity:

/b[.]n/Edit with Regexity

Special Case with Newlines

The regex wildcard character will match any character including spaces, letters, digits, punctuation, special characters, and more. The only character it does not match by default is the newline character \nEdit with Regexity. However, its behavior can be altered to match the newline character by turning on the s flag in your expression.

Alternatives

Some alternatives to the wildcard character can be hacked by using a combination of other character sets. For example, the following expression will serve the same function:

/[\s\S]/Edit with Regexity

Why does it work? It consists of two character sets:

These are both enclosed in a character class, meaning any one of them can be matched in any order. Since “any space character” and “anything except a space character” encapsulates all possible characters, this essentially works the same as the wildcard character.

Benjamin

Founder, owner, and sole content creator on RegexLand. Enjoys programming, blogging, and teaching others how to do the same. Read more...

Leave a Comment