How do you match any one character with a regular expression?
I am writing this question and the following answer for a general reference. A number of other questions on Stack Overflow sound like they promise a quick answer, but are actually asking something more specific.
Best Answer
Match any single character
.
character as a wildcard to match any single character.Example regex:
a.c
Match any specific character in a set
[]
to match any characters in a set.\w
to match any single alphanumeric character:0-9
,a-z
,A-Z
, and_
(underscore).\d
to match any single digit.\s
to match any single whitespace character.Example 1 regex:
a[bcd]c
Example 2 regex:
a[0-7]c
Match any character except ...
Use the hat in square brackets
[^]
to match any single character except for any of the characters that come after the hat^
.Example regex:
a[^abc]c
(Don't confuse the
^
here in[^]
with its other usage as the start of line character:^
= line start,$
= line end.)Match any character optionally
Use the optional character
?
after any character to specify zero or one occurrence of that character. Thus, you would use.?
to match any single character optionally.Example regex:
a.?c
See also