Extract Integer Part in String

Extract Integer Part in String

Why don't you just use a Regular Expression to match the part of the string that you want?

[0-9]

That's all you need, plus whatever surrounding chars it requires.

Look at http://www.regular-expressions.info/tutorial.html to understand how Regular expressions work.

Edit: I'd like to say that Regex may be a little overboard for this example, if indeed the code that the other submitter posted works... but I'd still recommend learning Regex's in general, for they are very powerful, and will come in handy more than I'd like to admit (after waiting several years before giving them a shot).

How to get integer values from a string in Python?

>>> import re
>>> string1 = "498results should get"
>>> int(re.search(r'\d+', string1).group())
498

If there are multiple integers in the string:

>>> map(int, re.findall(r'\d+', string1))
[498]

How to extract numbers from a string in Python?

If you only want to extract only positive integers, try the following:

>>> txt = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in txt.split() if s.isdigit()]
[23, 11, 2]

I would argue that this is better than the regex example because you don't need another module and it's more readable because you don't need to parse (and learn) the regex mini-language.

This will not recognize floats, negative integers, or integers in hexadecimal format. If you can't accept these limitations, jmnas's answer below will do the trick.

How can I extract an integer from within a string?

strtol doesn't find a number in a string. It converts the number at the beginning of the string. (It does skip whitespace, but nothing else.)

If you need to find where a number starts, you can use something like:

const char* nump = strpbrk(str, "0123456789");
if (nump == NULL) /* No number, handle error*/

(man strpbrk)

If your numbers might be signed, you'll need something a bit more sophisticated. One way is to do the above and then back up one character if the previous character is -. But watch out for the beginning of the string:

if ( nump != str && nump[-1] == '-') --nump;

Just putting - into the strpbrk argument would produce false matches on input like non-numeric7.

Extract digits from string - StringUtils Java

Use this code numberOnly will contain your desired output.

   String str="sdfvsdf68fsdfsf8999fsdf09";
String numberOnly= str.replaceAll("[^0-9]", "");

How to extract only integer part from a string in Python?

Import regex library:

import re

If you want to extract all digits:

numbers = []
texts = []
for string in m:
numbers.append(re.findall("\d+", string))
texts.append(re.sub("\d+", "", string).strip())

If you want to extract only first digit:

numbers = []
texts = []
for string in m:
numbers.append(re.findall("\d+", string)[0])
texts.append(re.sub("\d+", "", string).strip())

How can I extract a number from a string in JavaScript?

For this specific example,

 var thenum = thestring.replace(/^\D+/g, ''); // Replace all leading non-digits with nothing

In the general case:

 thenum = "foo3bar5".match(/\d+/)[0] // "3"

Here's a bonus: regex generator.

function getre(str, num) {
if(str === num)
return 'nice try';
var res = [/^\D+/g,/\D+$/g,/^\D+|\D+$/g,/\D+/g,/\D.*/g, /.*\D/g,/^\D+|\D.*$/g,/.*\D(?=\d)|\D+$/g];
for(var i = 0; i < res.length; i++)
if(str.replace(res[i], '') === num)
return 'num = str.replace(/' + res[i].source + '/g, "")';
return 'no idea';
};

function update() {
$ = function(x) { return document.getElementById(x) };
var re = getre($('str').value, $('num').value);
$('re').innerHTML = 'Numex speaks: <code>' + re + '</code>';
}
<p>Hi, I'm Numex, the Number Extractor Oracle.
<p>What is your string? <input id="str" value="42abc"></p>
<p>What number do you want to extract? <input id="num" value="42"></p>
<p><button onclick="update()">Insert Coin</button></p>
<p id="re"></p>

Extract a single (unsigned) integer from a string

$str = 'In My Cart : 11 12 items';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);


Related Topics



Leave a reply



Submit