How to copy a specific parameter from imported text file

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.

• 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. Commented May 17, 2021 at 8:04

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]


• 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 Commented Sep 20, 2021 at 13:21

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:

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:

• Thanks for your repeated help. I am still struggling with it. Why cant we have a unique way to copy a number from a string, irrespective of it being an integer, decimal or in exponential form? My problem is that the numbers I am trying to copy from large number of text files is in all possible forms depending upon magnitude. Also the definition of reg (= RegularExpression["Field $$V\\/cm$$:\\s*(\\d+)e?(\\d*)"];) which you suggested for exponential numbers, I am still not able to understand it properly and emulate for other strings. Will appreciate any further help. Thanks Commented Sep 30, 2021 at 5:52
• Here is a pattern that should match any number: RegularExpression["(\\-)?\\d+(\\.\\d+)?e\\d+"] | NumberString . RegularExpression is a powerfull tool, but it is pretty crytic and needs some effort. Unfortunately in MMA some characters, that are used for different purposes, must be doubled, what makes the syntax even more cryptic than necessary. Therefore, I would first learn it outside MMA. You will find a lot of stuff on the Internet. Commented Sep 30, 2021 at 8:44