Find and extract a number from a string
go through the string and use Char.IsDigit
string a = "str123";
string b = string.Empty;
int val;
for (int i=0; i< a.Length; i++)
{
if (Char.IsDigit(a[i]))
b += a[i];
}
if (b.Length>0)
val = int.Parse(b);
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 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"
Since this answer gained popularity for some reason, 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 digits from string - StringUtils Java
Use this code numberOnly will contain your desired output.
String str="sdfvsdf68fsdfsf8999fsdf09";
String numberOnly= str.replaceAll("[^0-9]", "");
Extracting numbers from vectors of strings
How about
# pattern is by finding a set of numbers in the start and capturing them
as.numeric(gsub("([0-9]+).*$", "\\1", years))
or
# pattern is to just remove _years_old
as.numeric(gsub(" years old", "", years))
or
# split by space, get the element in first index
as.numeric(sapply(strsplit(years, " "), "[[", 1))
Is there a better way to extract numbers from a string in python 3
Here's one way you can do the regex search that @Barmar suggested:
>>> import re
>>> int(re.search("\d+", "V70N-HN")[0])
70
Extract digits from a string in Java
You can use regex and delete non-digits.
str = str.replaceAll("\\D+","");
C: extract numbers from a string
You could try something like this:
- Walk the string until you find the first digit (use
isdigit
) - Use
strtoul
to extract the number starting at that positionstrtoul
returns the number- the second argument (
endptr
) points to the next character in the string, following the extracted number
- Rinse, repeat
Alternatively you could tokenize the string (using "(,+)"
) and try to strtoul
everything.
Extract Number from String in Python
You can filter
the string by digits using str.isdigit
method,
>>> int(filter(str.isdigit, str1))
3158
Related Topics
Finding the Variable Name Passed to a Function
How to Enable External Request in Iis Express
Difference Between Property and Field in C# 3.0+
What Are the Correct Version Numbers For C#
Using Resources Folder in Unity
Cleanest Way to Write Retry Logic
How to Generate Random Alphanumeric Strings
Parameterized Query For MySQL With C#
What's the @ in Front of a String in C#
Virtual Member Call in a Constructor
Create an Instance of a Class from a String
Multiple Levels in MVC Custom Routing
Protect .Net Code from Reverse Engineering
Difference Between Task and Thread
How to Read a CSV File into a .Net Datatable
An Existing Connection Was Forcibly Closed by the Remote Host