3
$\begingroup$

I'm interested in the general operation of extracting NumberString's after a certain keyword.

Here is a specific example

Consider the string:

string = "5.45m total area (approx.): 73.8 sq. m (794.3 sq. ft)"

I want to extract $73.8$ and $794.3$ and perform some operation on them $f$

This following code returns $5.45$, which I don't want.

StringCases[
           string
           , (m : NumberString) :> f[m]
]
{f["5.45"], f["73.8"], f["794.3"]}

Attempt 1

StringCases[
           string
           , "total"~~___~~(m : NumberString) :> f[m]
]
 {f["3"]}

this mysteriously returns the number $3$

Question

Write some pattern p such that

StringCases[
           string
          , p
]

returns

 {f["73.8"], f["794.3"]}
$\endgroup$

1 Answer 1

5
$\begingroup$

Answer to Attempt1:

The "___" eats away as much as it can. Finally this leaves only: "3"

Answer to Question:

p = "total" ~~ Shortest[___] ~~ m1 : NumberString ~~ Shortest[___] ~~ 
    m2 : NumberString :> {f[m1], f[m2]};
StringCases[string, p]

Note, this gives a double list. If you want a single list add "Flatten":

StringCases[string, p] // Flatten
$\endgroup$
2
  • $\begingroup$ Thanks, I didn't know about this! Is "___" set on Longest[] by default? $\endgroup$
    – Conor
    May 14, 2021 at 16:28
  • 2
    $\begingroup$ Ah, just found out from the documentation that ordinary expression patterns are Shortest[p] by default, while string patterns are Longest[p] by default. $\endgroup$
    – Conor
    May 14, 2021 at 16:30

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.