What string pattern will match an explicit asterisk (*) or at-sign (@)? The obvious example, StringMatchQ["*", "\*"], returns False. I can't find any mention of escaping them in string patterns, only in RegularExpressions, and that was in the advanced tutorial.

I thought it worth mentioning that the documentation for StringMatchQ gives the following solution to your problem:

Verbatim["p"] specifies the verbatim string "p", with * and @ treated literally.

So you'd be able to do something like:

StringMatchQ["*", Verbatim["*"]]
(* True *)

• It also mentions \\* explicitly in the table directly above that. – Brett Champion Apr 2 '15 at 18:52
• @BrettChampion It's not in the String Patterns tutorial though, which is where I'd have looked. I didn't put it in my answer because Sjoerd already covered that pretty well. – 2012rcampion Apr 2 '15 at 19:13

Yes, you need to escape a * character in a string pattern because it's a wildcard. To escape it, just prepend a backslash to it. Remember that to insert a backslash in a Mathematica string, you need to type two backslashes:

StringMatchQ["*", "\\*"]

(* => True *)

• Come to think about it, this is pretty deep stuff. In a normal string, an asterisk isn't a special character that needs to be escaped, so "*" is just the character with character code 42, and "\*" is a single character with code 63432. "\\*" equals {92, 42}, and only because it is used in a string pattern (where * is special) it is interpreted as an escape sequence and equals the literal "*" (42). Note that "*"=="\\*" yields False (whereas "*"=="*" yields True). – Sjoerd C. de Vries May 23 '13 at 21:59
• If you use regexes in shell scripts a lot, you'll get pretty familiar with this type of double (or triple) escaping =) – 2012rcampion Apr 2 '15 at 16:44