# Extract a number from a string

**URL:** <https://community.wolfram.com/t/extract-a-number-from-a-string/6136>\
**Category:** Questions\
**Tags:** mathematica\
**Created:** [July 11, 2015, 4:56am UTC](https://community.wolfram.com/t/extract-a-number-from-a-string/6136 "2015-07-11T04:56:14Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![bcolletti](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/bcolletti/32/12824_2.png) [@bcolletti](https://community.wolfram.com/u/bcolletti)\
**Post date:** [July 11, 2015, 4:56am UTC](https://community.wolfram.com/t/extract-a-number-from-a-string/6136/1 "2015-07-11T04:56:14Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![bsimpson141421356](https://avatars.discourse-cdn.com/v4/letter/b/ac91a4/32.png) [@bsimpson141421356](https://community.wolfram.com/u/bsimpson141421356)\
**Post date:** [July 11, 2015, 5:46am UTC](https://community.wolfram.com/t/extract-a-number-from-a-string/6136/2 "2015-07-11T05:46:18Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![girishav](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/girishav/32/28159_2.png) [@girishav](https://community.wolfram.com/u/girishav)\
**Post date:** [July 11, 2015, 9:09am UTC](https://community.wolfram.com/t/extract-a-number-from-a-string/6136/3 "2015-07-11T09:09:53Z")

</div>

You can also try–

```
StringSplit[x][[2]] // ToExpression

```

---

<div class="post-metadata">

**Author:** ![bcolletti](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/bcolletti/32/12824_2.png) [@bcolletti](https://community.wolfram.com/u/bcolletti)\
**Post date:** [July 12, 2015, 6:31pm UTC](https://community.wolfram.com/t/extract-a-number-from-a-string/6136/4 "2015-07-12T18:31:58Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![bcolletti](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/bcolletti/32/12824_2.png) [@bcolletti](https://community.wolfram.com/u/bcolletti)\
**Post date:** [July 12, 2015, 6:33pm UTC](https://community.wolfram.com/t/extract-a-number-from-a-string/6136/5 "2015-07-12T18:33:43Z")

</div>

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.
