0
$\begingroup$

I am working with the imported text files in Mathematica. Each text file has experimental data, measured at a several input parameter like "Field (V/cm):" How to ask Mathematica to copy the number after this string "Field (V/cm):" in the same line, but different number of spaces in between ?

Thanks for the help.

$\endgroup$
1
  • 1
    $\begingroup$ could you provide an example of what the data would look like? a snippet or just "pseudo data" at the moment I can't imagine in my head what your description describes. $\endgroup$
    – morbo
    May 17 at 8:04
1
$\begingroup$

You can use "StringCases" like:

s1 = "aaa aaa Field (V/cm):123.4";
s2 = "aaa aaa Field (V/cm):   123.4";

pat = "Field (V/cm):" ~~ " " ... ~~ x : NumberString;
StringCases[s1, pat :> x]
StringCases[s2, pat :> x]
StringCases[{s1, s2}, pat :> x]

enter image description here

$\endgroup$
1
  • $\begingroup$ How to do the same thing for coping any number after a string, including exponential part? Here, by using "NumberString" Mathematica only copies the number, and leaves the exponential part. For example, if s1 is "aaa aaa Field (V/cm):1.234e2", it only copies 1.234, but leaves e2. Thanks $\endgroup$
    – user49535
    Sep 20 at 13:21
0
$\begingroup$

To extract numbers in normal or exponential form from a text string we may use RegularExpression:

s1 = "aaa aaa Field (V/cm):123";
s2 = "aaa aaa Field (V/cm):123e2";

reg = RegularExpression["Field \\(V\\/cm\\):\\s*(\\d+)e?(\\d*)"];
StringCases[s1,reg :> If[NumericQ[ToExpression@"$2"], "$1 10^$2", "$1"]]
StringCases[s2,reg :> If[NumericQ[ToExpression@"$2"], "$1 10^$2", "$1"]]

This results in text output:

enter image description here

If you want numeric output you may use ToExpression:

StringCases[s1, 
  reg :> If[NumericQ[ToExpression@"$2"], "$1 10^$2", 
    "$1"]] // ToExpression
StringCases[s2, 
  reg :> If[NumericQ[ToExpression@"$2"], "$1 10^$2", 
    "$1"]] // ToExpression

Now you get numbers:

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.