# Input

A string.

### Output

The sum of all integers in the line.

### Constraints

1≤Length of line≤500

### Sample test Case

Input

the 5is 108 seCONd4 a


Output

117


Explanation

Sum is: 5+108+4=117

• Hi there, welcome to PPCG. Challenges for a single language are usually frowned upon here at PPCG. Maybe you could change it to a general challenge: given a string, output the sum of all numbers in the string, ignoring everything else (i.e. "the 5is 108 seCONd4 a" will result in 117 because 5+108+4=117). Also, every 'question' here should have a winning condition tag. In this case I assume it's [code-golf] (being the shortest possible solution)? – Kevin Cruijssen Mar 7 '19 at 9:54
• It appears that you've posted a similar question on SO, which tends to confirm that it was not designed to be a PPCG challenge and you are looking for 'usable' code rather than golfed code. I'd recommend to improve your original question on SO instead, so that it better fits the rules of the site. – Arnauld Mar 7 '19 at 10:15
• I've overhauled your post to fit our standards. Feel free to edit if the result doesn't suit you. – Adám Mar 7 '19 at 11:43
• – mbomb007 Mar 7 '19 at 17:12
• What about this case string x='-12hello3'; are you counting negative integers (i.e., -12+3 === -9)? – Shaun Bebbers Mar 15 '19 at 10:17

# 05AB1E (legacy), 5 bytes

.œþOà


Try it online or verify a few more test cases. (Times out for the larger test cases due to the .œ builtin.)

# 05AB1E, 11 6 bytes

þмS¡þO


Explanation:

.œ      # Get all partitions of the (implicit) input-string,
# which are all possible ways of dividing the input-strings into substrings
þ     # Only leave the items consisting of digits for each partition
# (in the new version of 05AB1E, an explicit € is required)
O    # Sum each inner list
à   # Pop and push its maximum
# (after which the result is output implicitly)

þм      # Only leave the non-digits of the (implicit) input-string
#  i.e. "the 5is 108 seCONd4 a" → "the is  seCONd a"
S     # Split it into a list of characters
#  → ["t","h","e"," ","i","s"," "," ","s","e","C","O","N","d"," ","a"]
¡    # Split the (implicit) input-string by each of these characters
#  → ["","","","","5","","","108","","","","","","","4","",""]
þ   # Remove the empty strings by only leaving the digits
#  → ["5","108","4"]
O  # And sum these numbers (which is output implicitly)
#  → 117

• Oh hey, clever usage of ¡! – Erik the Outgolfer Mar 9 '19 at 15:33

# Javascript, 34 32 bytes

s=>eval(s.match(/\d+/g).join+)

Match all digits and join them by a + turning it into 5+108+4, eval the result.
Only works on positive integers.

Saved 2 bytes thanks to Arnauld

f=
s=>eval(s.match(/\d+/g).join+)

g=()=>b.innerHTML = f(a.value)
g()
<input id=a value="the 5is 108 seCONd4 a" onkeyup="g()">
<pre id=b>

• I guess using string.length in the console to count characters isn't a good idea when it contains escape characters... Whoops, fixed it. Thx again – Bassdrop Cumberwubwubwub Mar 7 '19 at 10:19
• A slightly better option would be console.log(f.toString().length), but it's not 100% reliable either. – Arnauld Mar 7 '19 at 10:39
• Or just using TIO... – Jo King Mar 7 '19 at 11:35

# Perl 6, 14 bytes

{sum m:g/\d+/}


Try it online!

Anonymous code block that returns the sum of all series of digits

# R, 6448 45 bytes

After seeing the PowerShell entry I was able to golf this further.

function(s)eval(parse(,,gsub('\\D+','+0',s)))


Try it online!

• t= is sufficient here rather than text – Giuseppe Mar 8 '19 at 3:35
• Thanks, I always forget about partial matching, (and the string of ,,, til you get to the option you want). – CT Hall Mar 8 '19 at 3:36

# APL (Dyalog Unicode), 11 bytes

Anonymous tacit prefic function

+/#⍎¨∊∘⎕D⊆⊢


Try it online!

⊢ the argument

⊆ partitioned (runs of True become pieces, run of False are separators) by

∊ membership
∘ of
⎕D the set of digits

#⍎¨ evaluate each in the root namespace

+/ sum

# Zsh, 21 bytes

<<<$[${1//[^0-9]/+0}]


Try it online!

  ${1 } # the 5is 108 seCONd4 a${1//[^0-9]/+0}  # +0+0+0+05+0+0+0108+0+0+0+0+0+0+04+0+0
$[${1//[^0-9]/+0}] # 117


Unfortunately, bash complains because it interprets 0108 as octal. Zsh does not (unless setopt octalzeroes)

# Bash, 43 bytes

for n in ${1//[!0-9]/ };{((s+=n));};echo$s


Replaces every non-number with a space, and then sums them together.

-5 bytes thanks to GammaFunction

• – GammaFunction Mar 25 '19 at 1:12
• thank you! I have edited my post – vityavv Mar 25 '19 at 17:26

# Retina 0.8.2, 8 bytes

\d+
$* 1  Try it online! • The first line matches all numbers • The second line replaces these by 1s, repeated said number of times • The last line is a match, and counts the total number of 1s in the string # PowerShell, 29 bytes ($args-replace'\D+','+0')|iex


Try it online!

• I was able to improve my R answer due to the +0 part. – CT Hall Mar 8 '19 at 3:28

# Charcoal, 5 bytes

ＩΣ⁺ψＳ


Try it online! Link is to verbose version of code. Explanation: Charcoal's Sum operator automatically extracts numbers from a string, however if the string contains no non-digit characters then instead it takes the digital sum, so I concatenate a null byte to avoid this. The result is then cast back to string for implicit output.

sum.map read.words.map f
f x|'/'<x,x<':'=x
f _=' '


Try it online!

There's probably a better way, but this is the most obvious one.

# Python 3, 6359 56 bytes

Why not. Obligatory regex answer. Could probably dock off 6 by using Python 2, but whatever. Doesn't apply anymore since I'm using an eval approach instead of using map.

import re;x=lambda y:eval('+'.join(re.findall('\d+',y)))


Explanation:

import re; # Import regex module
x=lambda y: eval(                                 ) # Run as Python code
'+'.join(                     ) # Joined by '+'
re.findall('\d+',y) # A list of all matches of regex \d+ in string y


Try it online!

• Nice! In your TIO you should use z == l instead of z is l though. The current code can give false negatives if the numbers get high enough. – Jakob Mar 9 '19 at 17:48

# Java 10, 66 bytes

This is a lambda from String to int.

s->{var r=0;for(var n:s.split("\\D"))r+=new Long("0"+n);return r;}


Negative integers aren't supported. Presumably that's okay.

Try It Online

## Acknowledgments

• You can switch [^0-9] for \D for a few bytes, also you can switch long and String for var (though you will have to change the return type to int – Embodiment of Ignorance Mar 8 '19 at 6:13

## Ruby, 32 27 characters

->s{eval s.scan(/\d+/)*?+}


### Acknowledgments

• Welcome to PPCG! You could use *?+ instead of .join ?+ for -7 bytes. See ary * str – Conor O'Brien Mar 9 '19 at 6:41

# Cubix, 17 bytes

?|i.I!/s+q;;>p.O@


Try it online!

    ? |
i .
I ! / s + q ; ;
> p . O @ . . .
. .
. .


Watch it run

A fairly simple one. I in cubix will take the first integer in the input and push it to the stack. This has the effect of skipping all the characters. The rest of it is dealing with the additional and detecting the end of the input.

• I! Input an integer and test it for 0
• s+q;; If not zero, swap TOS (forces and initial 0) and add. Push result to the bottom of stack and clean out the top. Return to beginning.
• /i? If zero, redirect and do a character input to check
• |?;/ If positive (character) turn right into a reflect, this then pushes it back through the checker ? and turns right onto the pop from stack, leaving 0 on TOS. The IP then gets redirected back into the main loop.
• I>p.O@ if negative (end of input) turn left, do integer input, bring the bottom of stack to top, output and halt.

# PHP, 40 39 bytes

<?=array_sum(preg_split('(\D)',$argn));  Try it online! Run with php -nF input is from STDIN. Example: $ echo the 5is 108 seCONd4 a | php -nF sumint.php
117


f s|[(n,r)]<-reads s=n+f r|h:t<-s=f t|1>0=0


Try it online!

Makes use of reads.

This works because I simply scans the input stream for the next token that looks like a number, ignoring anything else.

~Ilj~#
>K+O@


Try it online!

+/⍎⍵
\D



Try it online!

+/ sum of

⍎ evaluation as APL of

⍵ the result of

\D replacing each non-digit with

  a space

# Japt-x, 5 bytes

f/\d+


Try it online!

• 3 bytes – Shaggy Mar 7 '19 at 20:33

# Attache, 23 bytes

Sum##N=>MatchAll&"\\d+"


Try it online!

A more interesting, but indirect, answer (37 bytes): {Sum!Reap[ReplaceF[_,/"\\d+",Sow@N]]}

## Explanation

Sum##N=>MatchAll&"\\d+"


This has the form:

f##g=>h&x


which, when expanded and parenthesized, becomes:

f ## (g => (h&x))


## composes two functions together, => creates a function mapping the left function over the result of the right function, and & binds an argument to a side of a function. For input _, this is equivalent to:

{ f[Map[g, h[_, x]]] }


First, then, we MatchAll runs of digit characters (\\d+). After, we convert each run to an actual integer using the N function. Finally, we take the sum of these numbers using Sum.

# APL(NARS), chars 13, bytes 26

{+/⍎¨⍵⊂⍨⍵∊⎕D}


test:

  f←{+/⍎¨⍵⊂⍨⍵∊⎕D}
f 'the 5is 108 seCONd4 a'
117


# C# (Visual C# Interactive Compiler), 117 111 bytes

a=>System.Text.RegularExpressions.Regex.Replace(a,@"\D+"," ").Split(' ').Select(x=>x==""?0:int.Parse(x)).Sum();


Try it online.

# Perl 5-p, 17 bytes

s/\d+/$\+=$&/eg}{


Try it online!

# Japt v2.0a0 -x, 3 bytes

Another test drive for my (very-WIP) interpreter.

q\D


Try it

q\D     :Implicit input of string
q       :Split on
\D     :  Non-digit characters (/[^0-9]/)
:Implicitly reduce by addition and output


# Java 8, 53 130 bytes

105 bytes + 25 bytes for regex import

s->{long c=0;for(Matcher m=Pattern.compile("\\d+").matcher(s);m.find();c+=new Long(m.group()));return c;}


Try it online!
Explanation

s->{                                                    // Lambda function
long c=0;                                           // Sum is zero
for(Matcher m=Pattern.compile("\\d+").matcher(s);   // Prepare regex matcher
m.find();                                       // While the string contains unused matches...
c+=new Long(m.group()));                        // Add those matches to the output
return c;                                           // Return the output
}

• I don't think this is correct: the (only) example by the OP suggests that consecutive digits should form a single integer, so "123" should produce 123, not 6 like your code does. – Michail Mar 9 '19 at 20:19
• That's unfortunate, I'll revise when I can – Benjamin Urquhart Mar 9 '19 at 21:48
• @Michail revised – Benjamin Urquhart Mar 24 '19 at 22:06

# SNOBOL4 (CSNOBOL4), 81 bytes

	S =INPUT
D	S SPAN('0123456789') . N REM . S	:F(O)
O =O + N	:(D)
O	OUTPUT =O
END


Try it online!

Swift, 109 bytes

func s(a:String){var d=0,t=0;a.forEach{(c) in if let e=Int(String(c)){d=d*10+e}else{t+=d;d=0}};t+=d;print(t)}


Try it online!

# Pip, 6 bytes

$+a@XI  Treats -123 as a negative integer. Try it online!  a Command-line input @XI Regex find all integers (XI is a variable predefined as the regex -?\d+)$+      Fold on +


If hyphens should be ignored rather than treated as minus signs, then the following works for 7 bytes:

\$+a@+XD


XD is a preset variable for \d; +XD adds the regex + modifier to it, making it match 1 or more digits.

# Java (JDK), 9894 93 bytes

s->java.util.Arrays.stream(s.split("\\D")).filter(t->!t.isEmpty()).mapToLong(Long::new).sum()


Try it online!

-4 bytes by using Long::new instead of Long::valueOf.
-1 byte by shortening the regex - if we're already removing empty strings later, making some extras when splitting is fine.

# Explained

s->                            // Lambda (target type is ToLongFunction<String>)
java.util.Arrays.stream(   // Stream the result of
s.split("\\D")        // splitting on non-digits
)
.filter(t->!t.isEmpty())   // Discard any empty strings
.mapToLong(Long::new)      // Convert to long
.sum()                     // Add up the stream's values.