I have large StringExpression that is used in StringCases. Some of the parts being pulled out are integer strings. These pull out fine. However, when I go to convert them from strings to integers with FromDigits (it can take a string of integers) in StringCases it errors but still converts the string to an integer. Minimal example:

BigStringExpr[anInteger_Symbol] := 
 StartOfString ~~ 
  anInteger : (Except["0", DigitCharacter] ~~ DigitCharacter ...) ~~ 

StringCases["1234", BigStringExpr[y] -> y]
(* {"1234"} *)

StringCases["1234", BigStringExpr[y] -> FromDigits@y]
FromDigits::nlst: The expression y is not a list of digits or a string of valid digits. >>
(* {1234} *)

Any ideas why this is happening? I know that I can convert after StringCases but I would prefer to keep it in there since it is a simple call and also helps with code readability.

  • 3
    $\begingroup$ Use RuleDelayed (:>) rather than Rule (->) in your StringCases; this will force evaluation of your FromDigits function at the opportune time, i.e. when $y$ has been given a value. $\endgroup$ – MarcoB Aug 19 '15 at 14:19
  • $\begingroup$ @MarcoB That did it. I have to keep that whole delayed thing in mind as I always forget its significance. Executes after replacement. {x, x} /. x -> RandomReal[] verses {x, x} /. x :> RandomReal[]. Thanks. $\endgroup$ – Edmund Aug 19 '15 at 14:25
BigStringExpr = (StartOfString ~~ 
    anInteger : (Except["0", DigitCharacter] ~~ DigitCharacter ...) ~~
      EndOfString :> ToExpression@anInteger)
StringCases["1234", BigStringExpr]



  • $\begingroup$ Thanks, but I need to define the string expression as I have because it is in a package. The method I've used allows me to reference the named parts of the expression from the package without using the full context path. See question 91851. $\endgroup$ – Edmund Aug 19 '15 at 14:29
  • 1
    $\begingroup$ @Edmund It is not the question of how you define the string expression that is the problem. It is the use of Rule. george2079 is using RuleDelayed (i.e., :>). This is the key point. This works StringCases["1234", BigStringExpr[y] :> FromDigits@y] $\endgroup$ – Jack LaVigne Aug 19 '15 at 21:11

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.