13
$\begingroup$

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

\w{2,3}

Any ideas?

$\endgroup$
2
  • 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$ May 2, 2013 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, 2013 at 9:28

1 Answer 1

19
$\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$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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