Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

It beats me to write the Mathematica pattern equivalent to the regex:


Any ideas?

share|improve this question
FWIW, there is no point in writing it as a string pattern if you're happy with it as a regular expression. String patterns and regular expressions are completely equivalent and should be considered nothing more than variant syntactical forms. – Oleksandr R. May 2 '13 at 20:12
I do not know what \w{2,3} is, but we have the RegularExpression function in Mathematica that handles all the usual regular expressions. – user5939 May 3 '13 at 9:28
up vote 16 down vote accepted

It's easy to search if you break it down:

Regex   Meaning             Mathematica command
\w      word character      WordCharacter
{2,3}   repeat 2 to 3 times Repeated[..., {2, 3}]

Combine it and use as:

StringMatchQ[{"a", "ab", "abc", "abcd"}, Repeated[WordCharacter, {2, 3}]]
(* {False, True, True, False} *)

However, you could just as well use the regular expression itself, which might be simpler if you're familiar with regexes:

StringMatchQ[{"a", "ab", "abc", "abcd"}, RegularExpression["\\w{2,3}"]]

The advantage of this is that it treats _ as a word character, like most flavours of regex, whereas WordCharacter does not consider it valid.

StringMatchQ["a_", #] & /@ {Repeated[WordCharacter, {2, 3}], RegularExpression["\\w{2,3}"]}
(* {False, True } *)
share|improve this answer
Thanks! I knew it was simple but couldn't find it in the documentation. – Marek Kowalczyk May 2 '13 at 20:12
@MarekKowalczyk Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Read the faq! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! – Dr. belisarius May 2 '13 at 20:15
@belisarius Thank you for the welcome message! – Marek Kowalczyk May 2 '13 at 20:23

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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