Regex to Get Number Only from String

Regex to get NUMBER only from String

\d+

\d represents any digit, + for one or more. If you want to catch negative numbers as well you can use -?\d+.

Note that as a string, it should be represented in C# as "\\d+", or @"\d+"

Regex for numbers only

Use the beginning and end anchors.

Regex regex = new Regex(@"^\d$");

Use "^\d+$" if you need to match more than one digit.


Note that "\d" will match [0-9] and other digit characters like the Eastern Arabic numerals ٠١٢٣٤٥٦٧٨٩. Use "^[0-9]+$" to restrict matches to just the Arabic numerals 0 - 9.


If you need to include any numeric representations other than just digits (like decimal values for starters), then see @tchrist's comprehensive guide to parsing numbers with regular expressions.

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.

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

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))

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).

Regex using javascript to return just numbers

Regular expressions:

var numberPattern = /\d+/g;

'something102asdfkj1948948'.match( numberPattern )

This would return an Array with two elements inside, '102' and '1948948'. Operate as you wish. If it doesn't match any it will return null.

To concatenate them:

'something102asdfkj1948948'.match( numberPattern ).join('')

Assuming you're not dealing with complex decimals, this should suffice I suppose.

Regular Expression to match only alphabetic characters

You may use any of these 2 variants:

/^[A-Z]+$/i
/^[A-Za-z]+$/

to match an input string of ASCII alphabets.

  • [A-Za-z] will match all the alphabets (both lowercase and uppercase).
  • ^ and $ will make sure that nothing but these alphabets will be matched.

Code:

preg_match('/^[A-Z]+$/i', "abcAbc^Xyz", $m);
var_dump($m);

Output:

array(0) {
}

Test case is for OP's comment that he wants to match only if there are 1 or more alphabets present in the input. As you can see in the test case that matches failed because there was ^ in the input string abcAbc^Xyz.

Note: Please note that the above answer only matches ASCII alphabets and doesn't match Unicode characters. If you want to match Unicode letters then use:

/^\p{L}+$/u

Here, \p{L} matches any kind of letter from any language

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 numbers from a string in PHP with Regex

Try this:

$only_digits = preg_replace('/\D+/', '', $string);

Upper \D - the opposite of \d - matches non-digits.

Demo (regex101)



Related Topics



Leave a reply



Submit