4

Considering two situations:

I have a string "F2.5" and Quantity["2.3s"]. How can the numeric value be extracted to have:

"F2.5"` -> 2.5

Quantity["2.3s"]` -> 2.3

Thanks!

MarcoB
  • 67,153
  • 18
  • 91
  • 189
SuTron
  • 1,708
  • 1
  • 11
  • 21

3 Answers3

6
StringDrop["F2.5", 1] // ToExpression

StringDrop["2.5F", -1] // ToExpression

and

List @@ Quantity["2.3s"] // First

or rather as @thils proposed, directly

Quantity["2.3s"] // First
SquareOne
  • 7,575
  • 1
  • 15
  • 34
5

Internal`StringToDouble seems applicable:

Internal`StringToDouble /@ {"F2.5", "2.5F"}
{2.5, 2.5}

The evaluated form of Quantity["2.3s"] is Quantity[2.3`,"Seconds"] therefore as already commented:

Quantity["2.3s"][[1]]
2.3

System`Convert`TableDump`ParseTable provides configurable options for processing strings.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
  • Nice ! I was looking in the $ImportFormats but failed to find something useful ... – SquareOne Jun 24 '15 at 12:31
  • Do you know in which functions this internal is used ? This works: ImportString["2.5F", "List"] but it does not for "F2.5" ... Interpreter["Number"]["F2.5"] or Interpreter["Number"]["2.5F"] do not work either ... – SquareOne Jun 24 '15 at 12:45
  • @SquareOne I seem to recall coming across an explicit use of Internal`StringToDouble by a built-in function but I cannot recall where at the moment. If I do later I'll let you know. – Mr.Wizard Jun 24 '15 at 12:53
3

This may be more robust, assuming you want to see the specific letter "F":

 ToExpression@StringCases[ #,
        {"F" ~~ s : NumberString -> s, 
         s : NumberString ~~ "F" -> s}] & /@
             {"F3.14", "2.718F","an embedded number F2.34 in a string"}

{{3.14}, {2.718}, {2.34}}

george2079
  • 38,913
  • 1
  • 43
  • 110