4
$\begingroup$

I'm trying to match a part of a string while imposing conditions on the patterns, e.g.:

StringCases["223", a: DigitCharacter ~~ b: DigitCharacter /; Unequal[a, b]]

what is very simple and works as expected:

(* {23} *) 

However when I try to specify the names of the patterns I've put before the condition with names I've retrieved from a string, say "ab":

Characters["ab"]

(* {a, b} *)

it does not work and the condition is not successfully enforced:

StringCases["223", a: DigitCharacter ~~ b: DigitCharacter /;Unequal[ToExpression /@ Characters["ab"]]]

(* {22} *)

Why doesn't it work, in spite of taking the precaution of converting the string characters returned from Characters to symbols? Aren't those strings, cast as symbols, proper variables (I'm suspicious since their color doesn't turn blue as usual and remains black, but do seem to work as regular variables)? How could I make it work this way?

$\endgroup$
1
  • 3
    $\begingroup$ try Unequal[{1, 1}] vs Unequal[1,1] $\endgroup$
    – kglr
    Jun 12 '20 at 23:57
7
$\begingroup$
StringCases["223", a : DigitCharacter ~~ b : DigitCharacter /; 
  Evaluate[Unequal @@ (ToExpression /@ Characters["ab"])]]
 {23}

Compare the evaluation of the three forms using Trace:

Trace[StringCases["223",  a : DigitCharacter ~~ b : DigitCharacter /; 
    Unequal[ToExpression /@ Characters["ab"]]] ] // Column

enter image description here

Trace[StringCases["223", a : DigitCharacter ~~ b : DigitCharacter /; 
   (Unequal @@ (ToExpression /@ Characters["ab"]))]] // Column

enter image description here

Trace[StringCases["223", a : DigitCharacter ~~ b : DigitCharacter /; 
    Evaluate[Unequal @@ (ToExpression /@ Characters["ab"])]]] // Column

enter image description here

$\endgroup$

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.