Does [DdoO]g
match dog ?
No. [DdoO]g
matches a single character 'D', or 'd', or 'o', or 'O', followed by a 'g' .
Regular Expression (Delimit with quotes) |
|
String (Delimit with quotes) |
|
The characters [
and ]
are not like regular characters, since they do not match characters
in the subject string, but indicate something about how the matching should be done.
Such characters are called metacharacters or operators.
You will see more of them in the next several pages.
But what if you really want to match [ and do not want its special meaning?
To do that, "escape" the [ by putting a backslash in front of it.
The regular expression \[
matches a single left bracket.
And (of course) \]
matches a single right bracket.
But what if you want to match backslash?
Then use two backslashes.
The regular expression \\
matches a single backslash.
Regular Expression | Matches | Does Not Match | |
---|---|---|---|
\[dog\] | [dog] | d | \[dog\] |
\\cat | \cat | cat | \\cat |
\\\\ | \\ | \\\\ | \\\ |
[\[\]] | [ or ] | \ | [] |
To match strings like
C:\Temp
and
D:\temp
use
[A-Z]:\\[Tt]emp
.
Bug Alert!
Some alphabetic characters get a special meaning when they are escaped.
For example, \s
does not match 's' but matches any whitespace character.
(More on this, later.)
Does [\\\[]
match \ ?
Does it match [ ?