# 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:

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

# GS2, 2 bytes

Wd

Try it online!

### How it works

For input x, this executes map(int, re.findall(r'-?\d+', x)) internally.
d    Compute their sum.
• Well, this was unexpected... Feb 12, 2016 at 16:25
• @Adnan: It's Dennis. Given enough time he can find a solution to any code golf in less than 4 bytes. Feb 17, 2016 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! Feb 17, 2016 at 11:58

# 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

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

# 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 # 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. ;) Feb 12, 2016 at 15:44 • @MartinBüttner While you're at it you could make the right character default to something too :O Feb 12, 2016 at 15:46 • hm, not a bad idea. I'll think about it. Feb 12, 2016 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 Feb 12, 2016 at 22:56 • @Downgoat This happens occasionally; I'm not sure why. Reloading the page seems to fix this. Feb 13, 2016 at 1:00 ## 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 :) Feb 13, 2016 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 • Saves a byte to use a whatevercode block: *.comb(/\d+/).sum Nov 29, 2022 at 2:59 • @Steffan I believe that may have been before the .sum method was added to the language. Which if I recall correctly would make it unavailable according to the rules. Dec 1, 2022 at 2:19 • That rule has changed since, you can now use languages newer than the challenge. I didn't know that Raku never had a sum method though Dec 1, 2022 at 4:23 • @Steffan. Originally Raku did not have sum of any sort. Partially because sum(1..5) could be written using the reduce meta operator [+](1..5). At some point it became obvious that there could be an optimization if the input was a range. A range could calculate its sum without going over its contents. So now the meta operator [+]... gets converted to sum which will allow for this optimization to take place. Basically the only reason sum was added is as an optimization. github.com/rakudo/rakudo/commit/… Jan 11, 2023 at 0:46 # 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? Feb 12, 2016 at 16:20
• @FryAmTheEggman Good question, I guess it will print nothing which in a numeric context is 0 ;-) Feb 12, 2016 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. Feb 12, 2016 at 18:28
• @Dennis I do though ._. Feb 12, 2016 at 18:34

⁽±Ḋ⌊

Try it Online!

p eval$_.scan(/\d+/)*?+ Attempt This Online! # PHP, 64 bytes <?php preg_match_all("/\d+/",$argv[1],$a);echo array_sum($a[0]);

Run it as

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? Feb 12, 2016 at 16:44

# Javascript, 32 39 bytes

s=>eval((s.match(/\d+/g)||[0]).join+)

f=
s=>eval((s.match(/\d+/g)||[0]).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')

# 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 Feb 12, 2016 at 16:49
• DigitCharacter doesn't work as written because it removes all the digits whereas we want to remove all the letters... Feb 12, 2016 at 18:18
• you are right. I was thinking of Total@ ToExpression@StringCases[#, DigitCharacter ..] & Feb 12, 2016 at 18:25
• I see! Yeah that change saves a byte. Feb 12, 2016 at 18:33
• 48 bytes by replacing Total with Tr Nov 1, 2022 at 1:53

# R, 46 43 bytes

sum(strtoi(strsplit(scan(,''),'\\D')[[1]]))

Explanation

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]]))
2:
[1] 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. Feb 18, 2016 at 13:22

# Factor + math.unicode sorting.human, 36 bytes

[ find-numbers [ real? ] filter Σ ]

Attempt This Online!

! "11a1"
find-numbers      ! { "" 11 "a" 1 }
[ real? ] filter  ! { 11 1 }
Σ                 ! 12

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

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:

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. – user45941 Feb 12, 2016 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)[[1]]) Uses strtoi to coerce to numeric # Ruby 45 bytes$*[0].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[1]:gsub("%d+",function(c)a=a+c end)print(a)

### Ungolfed

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
end)
print(a)            -- output a