return only Digits 0-9 from a String
I don't know if VBScript has some kind of a "regular expression replace" function, but if it does, then you could do something like this pseudocode:
reg_replace(/\D+/g, '', your_string)
I don't know VBScript so I can't give you the exact code but this would remove anything that is not a number.
EDIT: Make sure to have the global flag (the "g" at the end of the regexp), otherwise it will only match the first non-number in your string.
extract only 0-9 numbers from string
Try replacing the pattern [^0-9]*
with empty string:
SELECT REGEXP_REPLACE('abc 123 456k', '[^0-9]*', '')
This should strip off any non digit character, including whitespace.
Return only numbers from string
This is a great use for a regular expression.
var str = "Rs. 6,67,000"; var res = str.replace(/\D/g, ""); alert(res); // 667000
Regex that accepts only numbers (0-9) and NO characters
Your regex ^[0-9]
matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $
to the end:
^[0-9]*$
This accepts any number of digits, including none. To accept one or more digits, change the *
to +
. To accept exactly one digit, just remove the *
.
UPDATE: You mixed up the arguments to IsMatch
. The pattern should be the second argument, not the first:
if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))
CAUTION: In JavaScript, \d
is equivalent to [0-9]
, but in .NET, \d
by default matches any Unicode decimal digit, including exotic fare like ႒ (Myanmar 2) and ߉ (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9]
(or supply the RegexOptions.ECMAScript flag).
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))
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]", "");
Extract digits from a string in Java
You can use regex and delete non-digits.
str = str.replaceAll("\\D+","");
Get only numbers from string in python
you can use regex:
import re
just = 'Standard Price:20000'
price = re.findall("\d+", just)[0]
OR
price = just.split(":")[1]
Keep only numeric value from a string?
You do any of the following:
Use regular expressions. You can use a regular expression with either
A negative character class that defines the characters that are what you don't want (those characters other than decimal digits):
private static readonly Regex rxNonDigits = new Regex( @"[^\d]+");
In which case, you can do take either of these approaches:
// simply replace the offending substrings with an empty string
private string CleanStringOfNonDigits_V1( string s )
{
if ( string.IsNullOrEmpty(s) ) return s ;
string cleaned = rxNonDigits.Replace(s, "") ;
return cleaned ;
}
// split the string into an array of good substrings
// using the bad substrings as the delimiter. Then use
// String.Join() to splice things back together.
private string CleanStringOfNonDigits_V2( string s )
{
if (string.IsNullOrEmpty(s)) return s;
string cleaned = String.Join( rxNonDigits.Split(s) );
return cleaned ;
}a positive character set that defines what you do want (decimal digits):
private static Regex rxDigits = new Regex( @"[\d]+") ;
In which case you can do something like this:
private string CleanStringOfNonDigits_V3( string s )
{
if ( string.IsNullOrEmpty(s) ) return s ;
StringBuilder sb = new StringBuilder() ;
for ( Match m = rxDigits.Match(s) ; m.Success ; m = m.NextMatch() )
{
sb.Append(m.Value) ;
}
string cleaned = sb.ToString() ;
return cleaned ;
}
You're not required to use a regular expression, either.
You could use LINQ directly, since a string is an
IEnumerable<char>
:private string CleanStringOfNonDigits_V4( string s )
{
if ( string.IsNullOrEmpty(s) ) return s;
string cleaned = new string( s.Where( char.IsDigit ).ToArray() ) ;
return cleaned;
}If you're only dealing with western alphabets where the only decimal digits you'll see are ASCII, skipping
char.IsDigit
will likely buy you a little performance:private string CleanStringOfNonDigits_V5( string s )
{
if (string.IsNullOrEmpty(s)) return s;
string cleaned = new string(s.Where( c => c-'0' < 10 ).ToArray() ) ;
return cleaned;
}
Finally, you can simply iterate over the string, chucking the digits you don't want, like this:
private string CleanStringOfNonDigits_V6( string s )
{
if (string.IsNullOrEmpty(s)) return s;
StringBuilder sb = new StringBuilder(s.Length) ;
for (int i = 0; i < s.Length; ++i)
{
char c = s[i];
if ( c < '0' ) continue ;
if ( c > '9' ) continue ;
sb.Append(s[i]);
}
string cleaned = sb.ToString();
return cleaned;
}Or this:
private string CleanStringOfNonDigits_V7(string s)
{
if (string.IsNullOrEmpty(s)) return s;
StringBuilder sb = new StringBuilder(s);
int j = 0 ;
int i = 0 ;
while ( i < sb.Length )
{
bool isDigit = char.IsDigit( sb[i] ) ;
if ( isDigit )
{
sb[j++] = sb[i++];
}
else
{
++i ;
}
}
sb.Length = j;
string cleaned = sb.ToString();
return cleaned;
}
From a standpoint of clarity and cleanness of code, the version 1 is what you want. It's hard to beat a one liner.
If performance matters, my suspicion is that the version 7, the last version, is the winner. It creates one temporary — a StringBuilder()
and does the transformation in-place within the StringBuilder's in-place buffer.
The other options all do more work.
Related Topics
Difference Between the Keydown Event, Keypress Event and Keyup Event in Visual Studio
JSON.Net: Specify Converter for Dictionary Keys
Performance of Linq Any VS Firstordefault != Null
HTML Agility Pack - Removing Unwanted Tags Without Removing Content
Exporting Datagridview to CSV File
Edit Raw Pixel Data of Writeablebitmap
"The Semaphore Timeout Period Has Expired" Error for Usb Connection
Conditional Datagridview Formatting
Date Difference in Years Using C#
JSON.Net Custom Serialization with JSONconverter - How to Get the "Default" Behavior
A Pattern to Pause/Resume an Async Task
Why Is Foreach Loop Read-Only in C#
Monitor a Process's Network Usage
A Reproducible Example of Volatile Usage
How to Display the String HTML Contents into Webbrowser Control