Group Abstract Group Abstract

Message Boards Message Boards

0
|
7.3K Views
|
8 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Importing a number after a string?

Posted 4 years ago

Hi,

How to copy a real number after a string in a text file. This number can be in any form (integer /decimal /exponential). For example

aaaa bbb (xyz / cc.dd ee) : = 3.456e2

or

aaaa bbb (xyz / cc.dd ee) : = 345.6

or

aaaa bbb (xyz / cc.dd ee) : = 345

I need a function, which can copy the numerical value after "aaaa bbb (xyz / cc.dd ee) : =" irrespective of its form.

Thanks for the help.

POSTED BY: S G
8 Replies
Posted 4 years ago

Basically the same as Rohits last post, but without need to specify the leading part of the source strings:

s1 = "aaaa bbb (xyz / cc.dd ee) : = 3.456e2";
s2 = "pqr : = 345.6";
s3 = "stu / (v w x) : = 345";

Last /@ StringSplit[{s1, s2, s3}]
(* {"3.456e2","345.6","345"} *)
POSTED BY: Hans Milton
Posted 4 years ago

Hope it explains my problem little better

Not really. 1.23e2 is not a valid format for a number in WL. 1.23*^2 or 1.23*10^2 are valid. The code I provided converts the invalid form to the valid one and the result is a number, not a string.

If you want a string result then just split the string

StringSplit[#, "aaaa bbb (xyz / cc.dd ee) : = "] & /* First /@ {s1, s2, s3}
(* {"3.456e2", "345.6", "345"} *)
POSTED BY: Rohit Namjoshi
Posted 4 years ago
POSTED BY: S G
Posted 4 years ago

How about

extract[s_] := 
 s // StringSplit[#, "aaaa bbb (xyz / cc.dd ee) : = "] & // First // 
  Read[StringToStream[#], Number] &

s1 = "aaaa bbb (xyz / cc.dd ee) : = 3.456e2"
s2 = "aaaa bbb (xyz / cc.dd ee) : = 345.6"
s3 = "aaaa bbb (xyz / cc.dd ee) : = 345"

extract /@ {s1, s2, s3}
(* {345.6, 345.6, 345} *)
POSTED BY: Rohit Namjoshi
Posted 4 years ago
POSTED BY: Updating Name
Posted 4 years ago

Well, now you have changed the requirements. It would have been better if your original question stated the requirements clearly and completely.

In the s4 example there is a newline \n character separating the two cases. Is that always true or can s4 be like this?

s4 = "pqr : = 3 aaaa bbb (xyz / cc.dd ee) : = 3456e2";

or

s4 = "pqr : = 3aaaa bbb (xyz / cc.dd ee) : = 3456e2";

Is the number always preceded by : = or are there other possible character sequences?

If there is always a newline and always preceded by : = then

(s4 // StringSplit[#, " : = " | "\n"] &)[[2 ;; ;; 2]]
(* {"3", "3456e2"} *)

That will extract the numbers as strings, you can convert to numeric by mapping

Read[StringToStream[#], Number] & /@ {"3", "3456e2"}
(* {3, 345600} *)

s5 = "pqr : = 3
 aaaa bbb (xyz / cc.dd ee) : = 3456e2
abc : = 345.6";

(s5 // StringSplit[#, " : = " | "\n"] &)[[2 ;; ;; 2]]
(* {"3", "3456e2", "345.6"} *)
POSTED BY: Rohit Namjoshi
Posted 4 years ago
POSTED BY: S G
POSTED BY: Neil Singer
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard