Message Boards Message Boards

0
|
5856 Views
|
4 Replies
|
0 Total Likes
View groups...
Share
Share this post:
GROUPS:

Extract a number from a string

Posted 9 years ago

From the string x = "DIMENSION: 17" I want to extract the integer and load it into n (in general, the string need not end in 17). This command works:

n = StringCases[x,  "DIMENSION:" ~~ Whitespace ~~ (y : DigitCharacter ..) -> y] // First // ToExpression;

But there must be a much simpler way. What is it? Thankx.

Bruce

POSTED BY: Bruce Colletti
4 Replies
Posted 9 years ago

You can also try--

StringSplit[x][[2]] // ToExpression
POSTED BY: Girish Arabale
Posted 9 years ago

Girish, this is perfect, exactly what I sought. Thanks.

POSTED BY: Bruce Colletti
Posted 9 years ago

Is this simpler?

n = StringReplace[x, RegularExpression["\\D+"] -> " "] // ToExpression

which will handle any non-digit characters before and/or after the digits, but won't handle several groups of digits.

POSTED BY: Bill Simpson
Posted 9 years ago

Bill, this is shorter and thus better -- didn't think of using RegularExpression. Girish provided the solution I hoped was out there, and both replies are useful. Thanks.

POSTED BY: Bruce Colletti
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract