# How do I extract a number from a string?

I want to extract the number from an alphanumeric string. This is what I tried:

StringTake["thiru3", {6, 6}]


The result I got is 3, but it is still a String, which I determined by evaluating:

NumberQ[StringTake["thiru3", {6, 6}]]


which returns False.

-
 Related or possible duplicate: How do you convert a string containing a number in C scientific notation to a Mathematica number? – Mr.Wizard♦ Feb 27 at 4:04 @Mr.Wizard. I don't think it's a duplicate. This is about extracting a simple integer, not about a real an encoded in a string. – m_goldberg Feb 27 at 6:04

Try to use ToExpression, like this

ToExpression[StringTake["thiru3", {6, 6}]]


If you check it with Head[%] it confirms that it is an Integer

-
 StringCases["thiru3", x : NumberString :> ToExpression[x]]
(* {3} *)
First[%]
(* 3 *)
(* {True, Integer} *)

-
 As noted by ssch in Chris's answer, FromDigits[] might be better to use than ToExpression[]. – J. M.♦ Apr 4 at 14:55

Alternatively, and for multiple numbers:-

Map[FromDigits, Select[Characters["thiru37"], DigitQ]]


{3, 7}

Latterly

ToExpression@StringCases["thiru37", DigitCharacter]


{3, 7}

-
I think FromDigits is the best way since you will immediatly get a message printed in case it didn't work, that you can Check for if need be – ssch Dec 22 '12 at 19:23
s = "thiru3";
r = First@StringCases[s, RegularExpression["\\d+"]];
Needs["JLink"];
InstallJava[];
z = IntegerparseInt[r]


-
bbbut... why not ToExpression@r? – rm -rf Dec 22 '12 at 23:07
@rm-rf The sarcasm character doesn't display in your browser I guess. – Sjoerd C. de Vries Dec 22 '12 at 23:13
wish I could upvote twice. what an economical solution – acl Dec 23 '12 at 0:50

Like NumberString, DigitCharacter can be used to find numbers in a string. Use relative positioning in the string (like EndOfString) to localize your digits and ignore other numbers possibly appearing at other positions:

First@StringCases["0thi12ru3", (n:DigitCharacter~~EndOfString) :> ToExpression@n]

(* ==> 3 *)


This searches for exactly one number character right before the end of string. If the terminal number could have more than one digits, use DigitCharacter.. instead.

-

Try this.

Read[StringToStream[StringTake["thiru3", {6, 6}]]]

-