# Filter out and add up

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:

a1wAD5qw45REs5Fw4eRQR33wqe4WE


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


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

• 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 '16 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 '16 at 3:18
• Oh, I see what you mean. You're saying it has hyphens and this one doesn't. – Paul Feb 13 '16 at 3:20

# GS2, 2 bytes

Wd


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.

• Well, this was unexpected... – Adnan Feb 12 '16 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 '16 at 12:10

## Labyrinth, 8 bytes

Take that, Pyth...

?+
;,;!@


Try it online!

### Explanation

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.

• Awesome stuff Martin! – A Simmons Feb 17 '16 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!

q_A,s-Ser~]1b


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

# MATL, 8 bytes

1Y4XXXUs


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


# Retina, 22 11

\d+
$0$*1
1


Try it online!

11 bytes (!) saved thanks to Martin!

Basically just decimal to unary then count the 1s.

• 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 '16 at 15:44
• @MartinBüttner While you're at it you could make the right character default to something too :O – FryAmTheEggman Feb 12 '16 at 15:46
• hm, not a bad idea. I'll think about it. – Martin Ender Feb 12 '16 at 15:49

# Japt, 2 bytes

Nx


Test it online!

### How it works

N    // Implicit: N = (parse input for numbers, "strings", and [arrays])
x    // Sum. Implicit output.

• I'm getting an error "Japt.stdout" must be sent to an HTMLElement – Downgoat Feb 12 '16 at 22:56
• @Downgoat This happens occasionally; I'm not sure why. Reloading the page seems to fix this. – ETHproductions Feb 13 '16 at 1:00

# JavaScript ES6, 35 bytes

s=>eval(s.replace(/\D+/g,'+')+'.0')


### 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: .0 -0 +0 -"" -[] 0/10 0e-1 .1-.1  ### Alternate version, also 35 bytes s=>s.replace(/\d+/g,d=>t+=+d,t=0)|t  ### Another alternate version, 36 bytes s=>s.split(/\D/).map(d=>t+=+d,t=0)|t  ## Pyth, 1211 10 bytes ssM:z"\D"3   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! # Gol><>, 4 bytes iEh+  So short I need dummy text... • Perhaps you should explain your code with your extra space :) – nneonneo Feb 13 '16 at 17:56 # Perl 6, 18 bytes {[+] .comb(/\d+/)} {[+] .split(/\D/)}  ### Usage: 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  # Jelly, 6 bytes &-ṣ-ḌS  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.  # Perl, 21 + 1 = 22 bytes $_=eval join"+",/\d+/g


Requires the -p flag:

$perl -pe'$_=eval join"+",/\d+/g' <<< 'a1wAD5qw45REs5Fw4eRQR33wqe4WE'
97

• Does this work when there aren't any numbers? e.g. a? – FryAmTheEggman Feb 12 '16 at 16:20
• @FryAmTheEggman Good question, I guess it will print nothing which in a numeric context is 0 ;-) – andlrc Feb 12 '16 at 16:28

# Julia, 35 bytes

s->sum(parse,matchall(r"\d+","0"s))


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.

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

# PHP, 64 bytes

<?php preg_match_all("/\d+/",$argv,$a);echo array_sum($a);  Run it as php -f filterOutAndAddUp.php <test_case>  https://eval.in/517817 • 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 '16 at 16:44 # Javascript, 32 39 bytes s=>eval((s.match(/\d+/g)||).join+)  f= s=>eval((s.match(/\d+/g)||).join+) F=s=>document.body.innerHTML+='<pre>f(\''+s+'\') -> '+f(s)+'\n</pre>' F('a') F('5') F('10') F('1a1') F('11a1') F('4dasQWE65asAs5dAa5dWD') F('a1wAD5qw45REs5Fw4eRQR33wqe4WE') # Mathematica, 51 bytes Total@ToExpression@StringCases[#,DigitCharacter..]&  Catching the wrong end of the verbose Mathematica builtins. 1 Byte off with the help of @DavidC • DigitCharacter .. will save 1 byte – DavidC Feb 12 '16 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 '16 at 18:18 • you are right. I was thinking of Total@ ToExpression@StringCases[#, DigitCharacter ..] & – DavidC Feb 12 '16 at 18:25 • I see! Yeah that change saves a byte. – A Simmons Feb 12 '16 at 18:33 # R, 46 43 bytes sum(strtoi(strsplit(scan(,''),'\\D')[]))  Explanation  scan(,'') # Take the input string strsplit( ,'\\D') # Returns list of all numeric parts of the string [] # Unlists to character vector strtoi( ) # Converts to numeric vector sum( ) # Sums the numbers  Sample run > sum(strtoi(strsplit(scan(,''),'\\D')[])) 1: a1wAD5qw45REs5Fw4eRQR33wqe4WE 2: Read 1 item  97  Edit: Replaced [^0-9] with \\D. • 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 '16 at 13:22 ## PowerShell, 28 26 bytes $args-replace"\D",'+0'|iex


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' 97  Alternatively 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 ... # Gema, 39 characters <D>=@set{s;@add{${s;};$0}} ?= \Z=${s;0}


Sample run:

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


## Seriously, 13 bytes

,ú;û+@s≈MΣl


Try it online!

Explanation:

,ú;û+@s≈MΣl
,              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)

• @Adnan Good catch - it outputs the empty list with a. Should be a one-byte fix. – Mego Feb 12 '16 at 17:53

# Java, 70 bytes

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


# TI-Basic, 106 bytes

Works on TI-83/84 calculators!

Input Str1
"{0,→Str2
Str1+"N0→Str1
For(I,1,length(Ans
sub(Str1,I,1
If inString("0123456789",Ans
Then
Str2+Ans→Str2
Else
If ","≠sub(Str2,length(Str2),1
Str2+","→Str2
End
End
sum(expr(Ans


# Clojure/ClojureScript, 35 bytes

#(apply +(map int(re-seq #"\d+"%)))


# R, 50 bytes

Requires having gsubfn installed

sum(gsubfn::strapply(scan(,''),'\\d+',strtoi)[])


Uses strtoi to coerce to numeric

# Ruby 45 bytes

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


(First attempt at work, will revisit this)

# POSIX sh + tr + dc, 27 25 bytes

dc -e "0dtr -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.

## 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:gsub("%d+",function(c)a=a+c end)print(a)


### Ungolfed

a=0                 -- Initialize the sum at 0
arg: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
end)
print(a)            -- output a


# 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

• This prints nothing for input a. We are currently discussing whether that's valid or not. – Dennis Feb 13 '16 at 0:16
• @Dennis. Ok. I added another version to cover both eventualities. – Digital Trauma Feb 13 '16 at 0:27
• You could use ; instead of || to always add zero, for no harm. – Toby Speight Feb 15 '16 at 14:34
• @TobySpeight Yes, thats good - thanks! – Digital Trauma Feb 15 '16 at 18:01

# Python 2, 70 bytes

I am putting a Python answer just for fun.

import re
j=0
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!

• 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 '16 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.