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 *)
| improve this answer | |
  • $\begingroup$ It also mentions \\* explicitly in the table directly above that. $\endgroup$ – Brett Champion Apr 2 '15 at 18:52
  • $\begingroup$ @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. $\endgroup$ – 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 *)
| improve this answer | |
  • $\begingroup$ 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). $\endgroup$ – Sjoerd C. de Vries May 23 '13 at 21:59
  • $\begingroup$ If you use regexes in shell scripts a lot, you'll get pretty familiar with this type of double (or triple) escaping =) $\endgroup$ – 2012rcampion Apr 2 '15 at 16:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.