5
$\begingroup$

Why does this pick out everything instead of just beta?

Cases[{alpha, beta, mxyzptlk}, b_]

In a function you have to match the lead character. f[x_] := x^2, but f[x_] := p^2 doesn't do anything. Anyway, it would be very useful to have an "anything" character that is like * in Windows. Is there such a thing where a* would match alpha?

$\endgroup$
1
  • 2
    $\begingroup$ To close voter: since OP also asks about how to implement wildcard for pattern-matching, I think it's not proper to classify this question as simple mistake. $\endgroup$
    – xzczd
    Commented Nov 11, 2022 at 4:51

1 Answer 1

10
$\begingroup$

You've severely misunderstood how pattern matching of Mathematica works. _ is not wildcard character like ? or *. A simple example to tear off your illusion:

f[x_] := xaaaa^2
f[123]
(* xaaaa^2 *)

Please remember, one should never guess the meaning of unknown syntax. Consider starting from the tutorial Patterns in the document to learn how pattern matching works.

If you want to use wildcard character, here is a possibility:

Cases[{alpha, beta, mxyzptlk}, _?(StringMatchQ[SymbolName@#, "b*"] &)]
(* {beta} *)

If you don't bother to type the lengthy pattern every time, define a function e.g.:

wildcard[字符串_] := _?(StringMatchQ[SymbolName@#, 字符串] &)

Cases[{alpha, beta, mxyzptlk}, wildcard@"a*"]
(* {alpha} *)
$\endgroup$

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.