12
$\begingroup$

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

\w{2,3}

Any ideas?

$\endgroup$
  • 3
    $\begingroup$ 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. $\endgroup$ – Oleksandr R. May 2 '13 at 20:12
  • $\begingroup$ I do not know what \w{2,3} is, but we have the RegularExpression function in Mathematica that handles all the usual regular expressions. $\endgroup$ – user5939 May 3 '13 at 9:28
18
$\begingroup$

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 } *)
$\endgroup$
  • $\begingroup$ Thanks! I knew it was simple but couldn't find it in the documentation. $\endgroup$ – Marek Kowalczyk May 2 '13 at 20:12
  • $\begingroup$ @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! $\endgroup$ – Dr. belisarius May 2 '13 at 20:15
  • $\begingroup$ @belisarius Thank you for the welcome message! $\endgroup$ – Marek Kowalczyk May 2 '13 at 20:23

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.