Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top


The task is very simple. Given a non-empty string containing numbers, uppercase and lowercase letters, output the sum of the remaining numbers. For example:


Filtering out all the letters would result into:

 1   5  45   5  4    33   4

The sum of these numbers is 1 + 5 + 45 + 5 + 4 + 33 + 4 = 97. So the output would be 97.

Test Cases

a > 0
0 > 0
5 > 5
10 > 10
a0A > 0
1a1 > 2
11a1 > 12
4dasQWE65asAs5dAa5dWD > 79
a1wAD5qw45REs5Fw4eRQR33wqe4WE > 97

This is , so the submission with the least amount of bytes wins!

share|improve this question
I knew I had written that Labyrinth program before... here is the same challenge but with negative numbers as well (which makes a surprisingly big difference for some languages, so I don't think they're dupes). – Martin Ender Feb 12 at 18:06
@MartinBüttner Looks like that one doesn't include negative numbers: "-n (where n is an integer) is not counted as a negative n, but as a hyphen followed by n." – Paul Feb 13 at 3:18
Oh, I see what you mean. You're saying it has hyphens and this one doesn't. – Paul Feb 13 at 3:20

31 Answers 31

up vote 21 down vote accepted

GS2, 2 bytes


Try it online!

How it works

W     Read all numbers.
      For input x, this executes map(int, re.findall(r'-?\d+', x)) internally.
 d    Compute their sum.
share|improve this answer
Well, this was unexpected... – Adnan Feb 12 at 16:25
@Adnan: It's Dennis. Given enough time he can find a solution to any code golf in less than 4 bytes. – Deusovi Feb 17 at 12:10

Labyrinth, 8 bytes

Take that, Pyth...


Try it online!


The usual primer (stolen from Sp3000):

  • Labyrinth is 2D and stack-based. Stacks have an infinite number of zeroes on the bottom.
  • When the instruction pointer reaches a junction, it checks the top of the stack to determine where to turn next. Negative is left, zero is forward and positive is right.

What comes in really handy here is that Labyrinth has two different input commands, , and ?. The former reads a single byte from STDIN, or -1 at EOF. The latter reads an integer from STDIN. It does so skipping everything that isn't a number and then reads the first decimal number it finds. This one returns 0 at EOF, so we can't use it to check for EOF reliably here.

The main loop of the program is this compact bit:


With ? we read an integer (ignoring all letters), with + we add it to the running total (which starts out as one of the implicit zeroes at the stack bottom). Then we read another character with , to check for EOF. As long as we're not at EOF, the read character will be a letter which has a positive character code, so the IP turns right (from its point of view; i.e. west). ; discards the character because we don't need it and then we enter the loop again.

Once we're at EOF, , pushes a -1 so the IP turns left (east) instead. ; again discards that -1, ! prints the running total as an integer and @ terminates the program.

share|improve this answer
Awesome stuff Martin! – A Simmons Feb 17 at 11:58

CJam, 13 bytes

Fixed to work with input without numbers thanks to Dennis! Also saved a byte by replacing the letters array with an array of ASCII above code point 64. And then another byte saved by Dennis!


Simple transliteration from letters to spaces, then eval and sum. Try it online.

share|improve this answer

MATL, 8 bytes


Try it online!

1Y4      % predefined literal: '\d+'
XX       % implicit input. Match regular expression. Returns a cell array of strings
         % representing numbers
XU       % convert each string to a double. Returns a numeric array
s        % sum of numeric array
share|improve this answer

Retina, 22 11


Try it online!

11 bytes (!) saved thanks to Martin!

Basically just decimal to unary then count the 1s.

share|improve this answer
I should probably make $0 implicit if a substitution starts with $*. It's a very common pattern and that would have let you beat Pyth. ;) – Martin Ender Feb 12 at 15:44
@MartinBüttner While you're at it you could make the right character default to something too :O – FryAmTheEggman Feb 12 at 15:46
hm, not a bad idea. I'll think about it. – Martin Ender Feb 12 at 15:49

Japt, 2 bytes


Test it online!

How it works

N    // Implicit: N = (parse input for numbers, "strings", and [arrays])
x    // Sum. Implicit output.
share|improve this answer
I'm getting an error "Japt.stdout" must be sent to an HTMLElement – Downgoat Feb 12 at 22:56
@Downgoat This happens occasionally; I'm not sure why. Reloading the page seems to fix this. – ETHproductions Feb 13 at 1:00

JavaScript ES6, 35 bytes


How it works

First, we replace each string of non-digits with "+". There are basically four different ways that this could end up:

1. 1b23c456   => 1+23+456
2. a1b23c456  => +1+23+456
3. 1b23c456d  => 1+23+456+
4. a1b23c456d => +1+23+456+

Cases 1 and 2 are taken care of already. But we somehow need to fix the last + so that it doesn't cause an error. We could remove it with .replace(/\+$,""), but that's too expensive. We could append a 0 to the end, but that would affect the last number if the string does not end with a +. A compromise is to append .0, which is both a valid number on its own and doesn't affect the value of other integers.

Here's a few other values that would work as well:


Alternate version, also 35 bytes


Another alternate version, 36 bytes

share|improve this answer

Pyth, 12 11 10 bytes

    z        autoinitialized to input()
   : "\D"3   split on non-digits
 sM          convert all elements of resulting array to ints
s            sum

Fortunately, s (convert to int) returns 0 when applied to the empty string, so I don't have to worry about the fact that split("a1b", "\D+") returns ["", "1", ""]. Similarly, split("a", "\D+") returns ["", ""].

This even allows me to split on every non-digit individually, since 1 + 0 + 0 + 0 + 0 + 2 is the same thing as 1 + 2.

Thanks to Thomas Kwa for a byte!

share|improve this answer

Gol><>, 4 bytes


So short I need dummy text...

share|improve this answer
Perhaps you should explain your code with your extra space :) – nneonneo Feb 13 at 17:56

Perl 6, 18 bytes

{[+] .comb(/\d+/)}
{[+] .split(/\D/)}


my &code = {[+] .comb(/\d+/)}

say code 'a'; # 0
say code '0'; # 0
say code '5'; # 5
say code '10'; # 10
say code 'a0A'; # 0
say code '1a1'; # 2
say code '11a1'; # 12
say code '4dasQWE65asAs5dAa5dWD'; # 79
say code 'a1wAD5qw45REs5Fw4eRQR33wqe4WE'; # 97
share|improve this answer

Jelly, 6 bytes


Try it online!

How it works

&-ṣ-ḌS  Main link. Input: L (string)

&-      Take the bitwise AND of L's characters and -1.
        This attempts to cast to int, so '0' & -1 -> 0 & -1 -> 0.
        On failure, it returns the integer argument (if any), so 'a' & -1 -> -1.
  ṣ-    Split the resulting list at occurrences of -1.
    Ḍ   Convert each chunk from decimal to integer. In particular, [] -> 0.
     S  Compute the sum of the results.
share|improve this answer

Perl, 21 + 1 = 22 bytes

$_=eval join"+",/\d+/g

Requires the -p flag:

$ perl -pe'$_=eval join"+",/\d+/g' <<< 'a1wAD5qw45REs5Fw4eRQR33wqe4WE'
share|improve this answer
Does this work when there aren't any numbers? e.g. a? – FryAmTheEggman Feb 12 at 16:20
@FryAmTheEggman Good question, I guess it will print nothing which in a numeric context is 0 ;-) – andlrc Feb 12 at 16:28

Julia, 35 bytes


This is an anonymous function that accepts a string and returns an integer. To call it, assign it to a variable.

We use matchall to get an array consisting of matches of the regular expression \d+, which are just the integers in the string. We have to tack on a 0 to the front of the string, otherwise for cases like "a", we'd be summing over an empty array, which causes an error. We then apply parse to each string match, which converts to integers, and take the sum.

share|improve this answer
parse can become int if you don't mind the deprecation warning. – Dennis Feb 12 at 18:28
@Dennis I do though ._. – Alex A. Feb 12 at 18:34

PHP, 64 bytes

<?php preg_match_all("/\d+/",$argv[1],$a);echo array_sum($a[0]);

Run it as

php -f filterOutAndAddUp.php <test_case>

share|improve this answer
Welcome to Programming Puzzles and Stack Exchange. This is a great answer (+1), however it could be improved by adding a code explanation and breakdown. Also, could you use <? instead of <?php? – wizzwizz4 Feb 12 at 16:44

Javascript, 32 39 bytes



F=s=>document.body.innerHTML+='<pre>f(\''+s+'\') -> '+f(s)+'\n</pre>'


share|improve this answer

Mathematica, 51 bytes


Catching the wrong end of the verbose Mathematica builtins. 1 Byte off with the help of @DavidC

share|improve this answer
DigitCharacter .. will save 1 byte – DavidC Feb 12 at 16:49
DigitCharacter doesn't work as written because it removes all the digits whereas we want to remove all the letters... – A Simmons Feb 12 at 18:18
you are right. I was thinking of Total@ ToExpression@StringCases[#, DigitCharacter ..] & – DavidC Feb 12 at 18:25
I see! Yeah that change saves a byte. – A Simmons Feb 12 at 18:33

R, 46 43 bytes



                    scan(,'')                  # Take the input string
           strsplit(         ,'\\D')           # Returns list of all numeric parts of the string
                                    [[1]]      # Unlists to character vector
    strtoi(                              )     # Converts to numeric vector
sum(                                      )    # Sums the numbers

Sample run

> sum(strtoi(strsplit(scan(,''),'\\D')[[1]]))
1: a1wAD5qw45REs5Fw4eRQR33wqe4WE
Read 1 item
[1] 97

Edit: Replaced [^0-9] with \\D.

share|improve this answer
Welcome to Programming Puzzles and Code Golf. This is a great first answer; however it would be improved by adding a code explanation and breakdown, so we know how it works. – wizzwizz4 Feb 18 at 13:22
@wizzwizz4 Thanks, added. – Laterow Feb 18 at 13:36

PowerShell, 28 26 bytes


Takes input $args then does a regex -replace to swap the letters with +0, then pipes that to iex (short for Invoke-Expression and similar to eval).

PS C:\Tools\Scripts\golfing> .\filter-out-and-add-up.ps1 'a1wAD5qw45REs5Fw4eRQR33wqe4WE'


If you're OK with some extraneous output, you can do the following, also at 28 26 bytes:

$args-split"\D"|measure -s

This will take the input string $args and -split it into an array-of-strings on the non-numbers (removing them in the process). For example, 1a2b33 would turn into ['1','2','33']. We pipe that to Measure-Object with the -Sum parameter. Output would be like the below:

PS C:\Tools\Scripts\golfing> .\filter-out-and-add-up.ps1 'a1wAD5qw45REs5Fw4eRQR33wqe4WE'

Count    : 21
Average  : 
Sum      : 97
Maximum  : 
Minimum  : 
Property : 

Edit -- durr, don't need the [ ] in the regex since I'm no longer specifying a list of possible matches ...

share|improve this answer

Gema, 39 characters


Sample run:

bash-4.3$ gema '<D>=@set{s;@add{${s;};$0}};?=;\Z=${s;0}' <<< 'a1wAD5qw45REs5Fw4eRQR33wqe4WE'
share|improve this answer

Seriously, 13 bytes


Try it online!


,              push input
 ú;û+          push "abc...zABC...Z" (uppercase and lowercase English letters)
     @s        split on letters
       `≈`M    convert to ints
           Σ   sum
            l  length (does nothing to an integer, pushes 0 if an empty list is left, in the case where the string is all letters)
share|improve this answer
@Adnan Good catch - it outputs the empty list with a. Should be a one-byte fix. – Mego Feb 12 at 17:53

Java, 70 bytes

s->{int n=0;for(String i:s.split("\\D+"))n+=Long.valueOf(i);return n;}
share|improve this answer

TI-Basic, 106 bytes

Works on TI-83/84 calculators!

Input Str1
If inString("0123456789",Ans
If ","≠sub(Str2,length(Str2),1
share|improve this answer

Clojure/ClojureScript, 35 bytes

#(apply +(map int(re-seq #"\d+"%)))
share|improve this answer

R, 50 bytes

Requires having gsubfn installed


Uses strtoi to coerce to numeric

share|improve this answer

Ruby 45 bytes

$*[0].split(/[a-z]/i).map(&:to_i).inject 0,:+

(First attempt at work, will revisit this)

share|improve this answer

POSIX sh + tr + dc, 27 25 bytes

dc -e "0d`tr -sc 0-9 +`p"

Converts any run of non-digits (including the terminating newline) to + operator, pushes two zeros onto the stack (in case input begins with non-digit), adds them all and prints the result. There may be an extra zero remaining at bottom of stack, but we don't care about that.

share|improve this answer

Lua, 51 Bytes

Pretty short for once! Even shorter than Java! The input must be a command-line argument for it to work.

a=0 arg[1]:gsub("%d+",function(c)a=a+c end)print(a)


a=0                 -- Initialize the sum at 0
arg[1]:gsub("%d+",  -- capture each group of digits in the string
  function(c)       -- and apply an anonymous function to each of them
  a=a+c             -- sums a with the latest group captured
print(a)            -- output a
share|improve this answer

Bash + GNU utilities, 29

grep -Eo [0-9]+|paste -sd+|bc

If it is required to support input with no numbers (e.g. a), then we can do this:

Bash + GNU utilities, 38

1 byte saved thanks to @TobySpeight.

(grep -Eo [0-9]+;echo 0)|paste -sd+|bc
share|improve this answer
This prints nothing for input a. We are currently discussing whether that's valid or not. – Dennis Feb 13 at 0:16
@Dennis. Ok. I added another version to cover both eventualities. – Digital Trauma Feb 13 at 0:27
You could use ; instead of || to always add zero, for no harm. – Toby Speight Feb 15 at 14:34
@TobySpeight Yes, thats good - thanks! – Digital Trauma Feb 15 at 18:01

Python 2, 70 bytes

I am putting a Python answer just for fun.

import re
for i in map(int,re.findall('\d+',input())):j+=i
print j

Very simple and uses regex to find all the numbers in the input. Try it online!

share|improve this answer
In this context you have to use raw_input or switch to python3. A smaller version (py3, 56 bytes) : import re;print(sum(map(int,re.findall('\d+',input())))). – Dica Feb 18 at 14:01

Oracle SQL 11.2, 105 bytes

SELECT NVL(SUM(TO_NUMBER(COLUMN_VALUE)),0)FROM XMLTABLE(('"'||regexp_replace(:1,'[a-zA-Z]','","')||'"'));

The regex convert alpha characters to ','

XMLTABLE create one row per item in the string using ',' as the separator.

SUM the rows to get the result.

NVL is needed to account for a string with no digit.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.