Increment every number in a string

11

2

Given a string containing decimal numbers:

teststring134this 123test string54 100

increment every number in this string by one to give the new string

teststring135this 124test string55 101.

The string can be provided as:

  • a command line argument
  • STDIN
  • a hard-coded variable or function argument

Cover all possible positions for a number:

  • as a prefix for a word; 123test124test
  • as a suffix for a word; test123test124
  • inside a word; te123stte124st
  • alone test 123 testtest 124 test

Here's a non-golfed solution in Python:

NUMBERS = '0123456789'

def increment(s):
    out = ''

    number = ''
    for c in s:
        if c in NUMBERS:
            number += c
        else:
            if number != '':
                out += str(int(number) + 1)
                number = ''
            out += c

    if number != '':
        out += str(int(number) + 1)
        number = ''

    return out


print "\"%s\"" % (increment('teststring134this 123test string54 100'))

This is a code-golf question, shortest code wins.

The6P4C

Posted 2014-09-21T11:06:09.023

Reputation: 229

5

Fun fact: this can be done with 3 pure regex substitutions (no callbacks) http://stackoverflow.com/questions/12941362/is-it-possible-to-increment-numbers-using-regex-substitution/12942634#12942634 (that wouldn't be the golfiest way though)

– Martin Ender – 2014-09-21T11:19:40.603

4You specified input but not output. From your input spec I assume both STDOUT and and return value are fine. But can we also store the result in a hardcoded variable (just as we can take input from it)? – Martin Ender – 2014-09-21T11:23:32.207

Your code shouldn't work... Don't you need to declare NUMBERS as a global variable inside increment(s) or is it different in Python 2? – Beta Decay – 2014-09-21T14:44:21.117

1What about carrying? What happens to 999? – fluffy – 2014-09-21T17:13:03.820

3

possible duplicate of Multiply all numbers in a string

– Digital Trauma – 2014-09-21T18:52:00.750

Shucks, when I saw the title I thought this was about implementing inflationary language.

– Mike Mertsock – 2014-09-21T18:59:47.690

7What about negative numbers? What about numbers with a decimal point? What about numbers with a decimal point and nothing before it (except perhaps for a minus sign)? – Peter Taylor – 2014-09-21T20:45:54.780

@BetaDecay It works fine in Python 2 and 3, you can read variables from outer scopes. – flornquake – 2014-09-23T10:25:54.613

What about numbers with leading zeros? "A0000" -> "A1"? "A0001"? – Kobi – 2014-09-23T12:02:04.237

@BetaDecay You need to put an explicit declaration if you want to assign to outer scopes. – Bakuriu – 2014-09-23T16:44:52.233

Answers

23

Perl, 14 bytes

s/\d+/$&+1/ge

Requires the -p switch, which I have counted as one byte.

Example run

$ perl -p <(echo 's/\d+/$&+1/ge') <<< 'teststring134this 123test string54 100'
teststring135this 124test string55 101

Dennis

Posted 2014-09-21T11:06:09.023

Reputation: 196 637

5

Very similar to my answer here haha http://codegolf.stackexchange.com/a/37113/29438

– hmatt1 – 2014-09-21T20:20:52.380

12

Ruby, 30 24 bytes

$><<s.gsub(/\d+/,&:next)

Expects the input to be stored in s.

Martin Ender

Posted 2014-09-21T11:06:09.023

Reputation: 184 808

3Couldn't $1.next be used in the block? – August – 2014-09-21T12:29:10.033

@August nice, thanks! I didn't know next was that sophisticated. – Martin Ender – 2014-09-21T12:34:55.730

11

Vim - 13 keystrokes

0qqqqq^Al@qq@q

Expects the input to be the current line.

Or for finitely many numbers (e.g. 999) in 8 + ceil(log(n)) keystrokes:

0qq^Alq999@q

coyotebush

Posted 2014-09-21T11:06:09.023

Reputation: 211

I can't seem to make this work.... (I am using vim 7.0.237) – Jerry Jeremiah – 2016-11-11T02:24:41.397

10

JavaScript (ES6) - 28

H=k=>k.replace(/\d+/g,k=>++k)

Run by using H("test 123 234t").

soktinpk

Posted 2014-09-21T11:06:09.023

Reputation: 4 080

1You can take out the H= and just have it be an anonymous function. – Mama Fun Roll – 2016-11-10T14:29:29.070

8

Python 2 - 59

Supply the string as the variable n

import re;print re.sub('\d+',lambda x:`int(x.group())+1`,n)

Beta Decay

Posted 2014-09-21T11:06:09.023

Reputation: 21 478

8

Perl, 23

Assumes the input string is assigned to $_

s/\d+/@{[$&+1]}/g;print

grc

Posted 2014-09-21T11:06:09.023

Reputation: 18 565

6

C99 - 86 (GCC 4.9.0 and Visual C++ 2013)

Edit: Both GCC 4.9.0 (with -std=c99) and Visual C++ 2013 successfully build (with warnings) the same code without the includes. I didn't know you could do that! Thanks for the hint.

Edit: It didn't even occur to me that I should write it to the screen on the fly instead of creating the string and then printing it. That makes a huge difference. Thanks Dennis!

This is using a hard coded string but the contents of the string are not counted towards the total (the ="" is counted).

main(i){for(char*q,*s="test123test999test-1test";i=strtol(s,&q,0),*s;q>s?printf("%d",i+1,s=q):putchar(*s++));}

Basically it runs through the string one character at a time checking each to see if it is an integer. If it is then it increments the integer and writes it to the output otherwise it copies the current character to the output.

This leaks the hardcoded string because it increments s.

Jerry Jeremiah

Posted 2014-09-21T11:06:09.023

Reputation: 1 217

Produces incorrect output when a number is preceded by a space (). – None – 2019-01-31T09:14:23.267

1I'm sure you can get rid of some of the includes and it will still compile fine with gcc. – Martin Ender – 2014-09-21T11:58:57.753

1Will this work with a string containing e.g. 99? – anatolyg – 2014-09-21T16:32:29.240

@MartinBüttner: Yes but then it wouldn't be valid C, just something that happens to work on gcc. – R.. GitHub STOP HELPING ICE – 2014-09-21T18:46:00.977

@R.. That's generally allowed on PPCG though. I've seen (and subsequently done) it quite often without anyone complaining. – Martin Ender – 2014-09-21T19:58:16.227

Yes, and it's a general peeve of mine. The language should be listed as "GCC" or "C on [particular arch/etc. the hacks happen to work on]" or similar, rather than C, if it's not actually valid C. :-) – R.. GitHub STOP HELPING ICE – 2014-09-21T20:01:13.543

@MartinBüttner I'll try! I was using Visual C++ to compile it. Maybe GCC is more forgiving. – Jerry Jeremiah – 2014-09-21T21:18:00.090

@R I have labelled it with the compilers I tested it on. I hope that's ok. – Jerry Jeremiah – 2014-09-21T21:45:32.433

>

  • You can change the loop to for(;i=strtol(s,&q,0),*s;(q>s)?printf("%d",i+1,s=q):putchar(*s++));. This make p and o obsolete. 2. You can declare i as main(i).
  • < – Dennis – 2014-09-21T22:13:30.087

    I only make this 87 characters without the initialisation of s already. There are also a couple of other savings to be had. You can use char*s without the space and you do not need the brackets round (q>s). You can also move the declaration and initialisation of s and q inside the for loop to save a semi-colon. – Alchymist – 2014-09-23T11:08:22.287

    @Alchymist thanks for the tips – Jerry Jeremiah – 2014-09-24T21:32:32.353

    5

    J (20)

    Expects the input to be stored in the variable a.

    '\d+'>:&.".rxapply a
    

    Test:

       a=:'teststring134this 123test string54 100'
       '\d+'>:&.".rxapply a
    teststring135this 124test string55 101
    

    marinus

    Posted 2014-09-21T11:06:09.023

    Reputation: 30 224

    5

    (f?)lex (39)

    File inc.l:

    %%
    [0-9]+ printf("%d",atoi(yytext)+1);
    

    Compile:

    $ flex inc.l
    $ gcc lex.yy.c -o inc -lfl
    

    Run:

    $ echo 'teststring134this 123test string54 100' | ./inc
    teststring135this 124test string55 101
    
    $ i='(-: 2 empty bottles of beer :-)'
    $ tty=$(tty)
    $ for n in {2..5} ; do i=$(./inc<<<$i|tee $tty) ; done
    (-: 3 empty bottles of beer :-)
    (-: 4 empty bottles of beer :-)
    (-: 5 empty bottles of beer :-)
    (-: 6 empty bottles of beer :-)
    

    I did not test this with the original lex. Comments are welcome.

    user19214

    Posted 2014-09-21T11:06:09.023

    Reputation:

    1

    You can drop the trailing %% since this is no user code: http://flex.sourceforge.net/manual/User-Code-Section.html#User-Code-Section

    – Josh – 2014-09-24T19:41:14.907

    Hey... yes! I tried but without trailing newline and that failed... then I didn't try to add the final newline... ;-) ...stupid mistake! – None – 2014-09-24T20:54:24.350

    3

    Emacs - 20 characters

    C-M-% [0-9]+ RET \,(1+ \#0) RET !
    

    Requires text to be processed to be present in the current buffer. I counted C-M-% as one character here since it can be entered with one keystroke when holding down three modifiers.

    user16727

    Posted 2014-09-21T11:06:09.023

    Reputation: 51

    3

    Racket 74

    (define(f x)(regexp-replace* #px"\\d+"x(λ(m)(~a(+ 1(string->number m))))))
    

    Matthew Butterick

    Posted 2014-09-21T11:06:09.023

    Reputation: 401

    3

    GNU sed, 304 (including 1 for -r flag)

    I close-voted this question as a possible duplicate, but this is perhaps contrary to that because this answer can't be trivially changed to work there. By far the longest answer though.

    Inspired by this example from the sed documentation, though it needed some work to handle multiple numbers in a string:

    :d
    s/9([^0-9]+|$)/_\1/g
    td
    s/8(_*)([^0-9]+|$)/9\1\2/g
    s/7(_*)([^0-9]+|$)/8\1\2/g
    s/6(_*)([^0-9]+|$)/7\1\2/g
    s/5(_*)([^0-9]+|$)/6\1\2/g
    s/4(_*)([^0-9]+|$)/5\1\2/g
    s/3(_*)([^0-9]+|$)/4\1\2/g
    s/2(_*)([^0-9]+|$)/3\1\2/g
    s/1(_*)([^0-9]+|$)/2\1\2/g
    s/0(_*)([^0-9]+|$)/1\1\2/g
    s/(^|[^0-9_]+)(_+)/\11\2/g
    y/_/0/
    

    Output:

    $ for s in "teststring134this 123test string54 100" "123test" "test123" "te123st" "test 123 test" ; do echo "$s" | sed -rf incr.sed ; done
    teststring135this 124test string55 101
    124test
    test124
    te124st
    test 124 test
    $ 
    

    Note this temporarily inserts _ characters, so could lead to incorrect results if there are _ in the input stream. As a mitigation to this, we can replace the _ in the sed script with some non-printable character (e.g. ASCII 0x07 BEL), and assume the input stream contains only printable ASCII. This seems to work fine when I test it.

    Digital Trauma

    Posted 2014-09-21T11:06:09.023

    Reputation: 64 644

    2

    Lua - 68 characters

    d='(%D-)'for k,i,j in s:gmatch(d..'(%d+)'..d)do io.write(k,i+1,j)end
    

    Expects the input to be stored in s.

    AndoDaan

    Posted 2014-09-21T11:06:09.023

    Reputation: 2 232

    2

    CJam, 67 58 53 48 31 characters

    This question is like the worst question for CJam. No regex, no pattern matching, no exception catching. But here we go (#YOLO)

    Sl+_A,sNerN%\[_A,s-Ner~]:)]zs1>
    

    This one splits the string in group of just alphabets and just digits. The increments each digit and stitches back the two array taking one element of each at a time.


    Previous solution:

    L_l{:Ci57-zA<:RC*+:N\R!N*NNW?i):NL?+RLC?@R*}/NL?
    

    Try it online here

    How it works:

    Basic idea is to keep storing the character separately in a string if it is a digit and dump the incremented value to the final string once we get a non digit character.

    L_                                               "Push two empty strings to stack,"
                                                     "first representing the final string"
                                                     "and second, the current ongoing number";
      l{                                       }/    "Run this block for each character of input string";
        :Ci                                          "Store the character to C and convert to"
                                                     "its ASCII equivalent integer";
           57-zA<:R                                  "Subtract 57 from the integer and compare"
                                                     "its absolute value with 10. Numeric character"
                                                     "would result to true here. Store the result in R";
                   C*+:N                             "Take either 0 or 1 characters from C based"
                                                     "on value of R, add it to the second string"
                                                     "from first step. Also store the value in N";
                        \                            "Switch the strings. Now the string containing"
                                                     "the final result string is at top of stack";
                         R!N*                        "If the character was not a digit and N contains a number in it";
                             NNW?i):NL?+             "Convert N to number and increment it."
                                                     "If N is blank, take 0 instead. Put the final"
                                                     "value back in N and add it to the final result string";
                                        RLC?         "If the character was not a digit, push it to stack";
                                            @R*      "Put the ongoing numeric string back to top of stack";
                                                 NL? "This is to handle the case when the last number"
                                                     "is not followed by a string, so stack will"
                                                     "have a string at top. Push the value of N to stack in that case";
    

    Optimizer

    Posted 2014-09-21T11:06:09.023

    Reputation: 25 836

    1

    Cobra - 88

    do(s='')=RegularExpressions.Regex.replace(s,'\d+',do(m as Match)='[int.parse("[m]")+1]')
    

    Οurous

    Posted 2014-09-21T11:06:09.023

    Reputation: 7 916

    1

    C# - 178 169 157 characters

    This assumes that numbers like 999 are allowed to overflow to 000 and that -+,.E are not part of a number.

    class T{static void Main(){var a="".ToCharArray();for(int b=1,c,i=a.Length;i-->0;b=48>c|c>57?7:b>0?c>56?a[i]='0':++a[i]*0:b)c=a[i];System.Console.Write(a);}}
    

    Better readable form:

    class T
    {
        static void Main()
        {
            var a="7teststring134this 123test string59 100".ToCharArray();
    
            for (int b=3, c, i=a.Length; i-->0;
                b=48>c|c>57
                    ?7
                    :b>2
                        ?c>56?a[i]='0':++a[i]*0
                        :b
            ) c=a[i];
    
            System.Console.Write(a);
            System.Console.ReadKey();
        }
    }
    

    I'm new here, never tried code golf before, just gave it a try :)

    I wonder if anyone has ideas to get it even shorter...

    To participate with C# it would be nice if we could omit all the necessary framework around the actual code - then this would only have 82 chars, and that without calling any powerful system functions.


    The same with pointers (182 chars):

    class T
    {
        unsafe static void Main()
        {
            char[] a="7teststring134this 123test string59 100".ToCharArray();
    
            int b=3;
            fixed (char* s=&a[0])
                for (var p=s+a.Length; p-->s; )
                    b=*p<48|*p>57
                        ?7
                        :b>2
                            ?*p>56?*p='0':++*p*0
                            :b;
    
            System.Console.Write(a);
            System.Console.ReadKey();
        }
    }
    

    Now without overflowing, this correctly handles the 999 case (223 chars):

    class T
    {
        static void Main()
        {
            var s=new System.Text.StringBuilder("9999teststring134this 123test string99 100");
    
            for (int b=3, c, i=s.Length; i-->0; )
            {
                c=s[i];
                b=48>c|c>57
                    ?b>8?8:7
                    :b>2
                        ?c>56?c-(s[i]='0'):++s[i]*0
                        :b;
                if (b>8&i<1|b==8) s.Insert(i+9-b, '1');
            }
    
            System.Console.Write(s);
            System.Console.ReadKey();
        }
    }
    

    Another different older one, it reads from standard input and uses recursion:

    namespace System {
        using C=Console;
        class T {
            class t {
                byte b=1;
                string s="";
                void R() {
                    var c=C.Read();
                    if (c>31) {
                        R();
                        if (48>c|c>57) b=1;
                        else if (b==1) c=c==57?48:++c*b--;
                        s=(char)c+s;
                    }
                }
                public t() {
                    R();
                    C.Write(s);
                }
            }
            static void Main() {
                new t();
                C.ReadKey();
            }
        }
    }
    

    Note: Console.ReadKey(); and the string itself should not be counted.

    I improved this already multiple times, see comments. There is still room for more improvements, I would say :) And sorry for the length, but I think the different versions are interesting enough to keep them...

    maf-soft

    Posted 2014-09-21T11:06:09.023

    Reputation: 261

    no, getting rid of the "environment" isn't allowed. i reckon in your second code after if(c==57) you could write c--; instead of c=48;, what about the ternary operator too. there is infact a lot of golfing tricks. maybe you should visit http://codegolf.stackexchange.com/questions/2203/tips-for-golfing-in-c

    – proud haskeller – 2014-09-23T17:18:15.500

    Thanks, I know nothing about golf :) everything you see here was invented by me ;-) 57-1 isn't 48. So I don't understand. – maf-soft – 2014-09-23T17:22:43.770

    Oops :-) :-) :-) :-) – proud haskeller – 2014-09-23T17:24:19.350

    I don't really know C# well, but I guess you can use some operator to stick them together like ... ? ... : c++*b-- – proud haskeller – 2014-09-23T17:51:04.003

    btw sorry for sending you the C tips instead of the C# tips: http://codegolf.stackexchange.com/questions/173/tips-for-code-golfing-in-c

    – proud haskeller – 2014-09-23T17:53:53.580

    Let us continue this discussion in chat.

    – maf-soft – 2014-09-23T19:57:40.870

    Thanks a lot for the hints. I improved it a lot now. Any more ideas? ... It's not nice to downvote my solution without a comment. Please tell me why you don't like it ... – maf-soft – 2014-09-25T13:17:10.913

    it's not me, I didn't downvote your answer – proud haskeller – 2014-09-25T13:18:19.650

    @proud Sorry, I put two independent messages in one. Of course I didn't mean you. – maf-soft – 2014-09-25T13:26:57.453

    1

    Groovy, 38 bytes

    {it.replaceAll(/\d+/,{(it as int)+1})}
    

    Uggghhh... I absolutely hate the words replace and all, they ruin all regex golfs for me.

    Magic Octopus Urn

    Posted 2014-09-21T11:06:09.023

    Reputation: 19 422

    1(it as int)+1it.next() – manatwork – 2016-11-11T12:28:52.680

    0

    C# (Visual C# Interactive Compiler) with command-line option /u:System.Text.RegularExpressions.Regex;System.Int32, 40 bytes

    Replace(n,"\\d+",m=>Parse(m.Value)+1+"")
    

    Expects input to be in a variable named n.

    Try it online!

    Embodiment of Ignorance

    Posted 2014-09-21T11:06:09.023

    Reputation: 7 014

    2Invalid, cannot expect input in a variable – ASCII-only – 2019-01-31T09:10:05.937

    @ascii-only This question seems to explicitly allow it' though personally, I would try to stick to today's input standards – Jo King – 2019-01-31T11:45:23.040

    Oh wait :/ ew this question – ASCII-only – 2019-01-31T23:57:02.737

    0

    PHP - 91 Bytes

    <?$i=fgets(STDIN);for($n=0;$n<strlen($i);$n++)if(is_numeric($i[$n]))$i[$n]=$i[$n]+1;echo$i;
    

    I don't wanted to use regular expressions. PHP isn't capable to directly increment a string offset, so, I needed to add some bytes on the increment step. This one line script remembers me a very dark age of the PHP scripting...

    Alexandre Teles

    Posted 2014-09-21T11:06:09.023

    Reputation: 101

    I have observed just now that the question asks you to increment the result number of a sequence of algarisms. This answer is incorrect. But I really feel that the op should add more details about what he wants. – Alexandre Teles – 2014-09-23T13:15:47.023

    0

    K, 56

    {" "/:{,/$(`$a)^`$$1+"I"$a:_[;x]@&~~':x in .Q.n}'" "\:x}
    

    tmartin

    Posted 2014-09-21T11:06:09.023

    Reputation: 3 917

    0

    sed and bash - 40 (including invocation and pipes)

    $ cat << EOF |sed 's/[0-9]\+/$((\0+1))/g;s/^/echo /'|bash
    teststring134this 123test string54 100
    123test
    test123
    te123st
    test 123 test
    EOF
    

    Outputs:

    teststring135this 124test string55 101
    124test
    test124
    te124st
    test 124 test
    

    mgjk

    Posted 2014-09-21T11:06:09.023

    Reputation: 101

    I tried this test string: 42;rm -rf / It worked the first time. – Dennis – 2014-09-26T13:22:49.207

    2You can change \0 to & (-1 char), $((…)) to $[…] (-2 chars), s/^/echo / to iecho \\ (-2 chars) to shorten your current code. However better fix the bug mentioned by @Dennis first. (He wrote “It worked the first time” for fun and as hint about the issue. Actually your code fails on input containing ;, #, \…``, $(…) and maybe other special characters too.) – manatwork – 2014-09-26T14:34:39.947

    Arbitrary code execution is a feature :-) – mgjk – 2014-09-26T14:37:05.350

    There may be no way to go this route without some kind of input restrictions and keeping the code tiny. The nature of the solution is to translate the input and use an interpreter to do the math since sed can't do it. As soon as user input hits an interpreter, the escaping is nuts. Short of the previous sed example, sed can't do math. – mgjk – 2014-09-26T15:43:06.170

    Somewhat shorter: eval echo \sed 's/[0-9]+/$[&+1]/g'`` - still has the code injection problem though, as per my answer to another similar question http://codegolf.stackexchange.com/a/37145/11259

    – Digital Trauma – 2014-09-26T18:55:30.197

    Scoring appears to be a bit off - sed 's/[0-9]\+/$((\0+1))/g;s/^/echo /'|bash is 43 bytes by my count – Digital Trauma – 2014-09-26T18:58:42.320

    0

    Java 7, 119 bytes

    void c(String s){for(String x:s.split("(?=[^\\d]+)|(?<=[^\\d]+)"))System.out.print(x.matches("\\d+")?new Long(x)+1:x);}
    

    If the requirement is a program instead of just a function, then it's 149 bytes:

    class M{public static void main(String[]a){for(String x:a[0].split("(?=[^\\d]+)|(?<=[^\\d]+)"))System.out.print(x.matches("\\d+")?new Long(x)+1:x);}}
    

    Ungolfed & test code:

    Try it here.

    class M{
      static void c(String s){
        for(String x : s.split("(?=[^\\d]+)|(?<=[^\\d]+)")){
          System.out.print(x.matches("\\d+")
                            ? new Long(x) + 1
                            : x);
        }
      }
    
      public static void main(String[] a){
        c("123test");
        System.out.println();
        c("test123");
        System.out.println();
        c("te123st");
        System.out.println();
        c("test 123 test");
        System.out.println();
        c("7teststring134this 123test string59 100");
      }
    }
    

    Output:

    124test
    test124
    te124st
    test 124 test
    8teststring135this 124test string60 101
    

    Kevin Cruijssen

    Posted 2014-09-21T11:06:09.023

    Reputation: 67 575

    0

    DASH, 16 bytes (noncompeting)

    rstr[R"\d+""g"+1
    

    This returns a function/partial application.

    Usage:

    rstr[R"\d+""g"+1]"test 123 234t"
    

    Explanation

    rstr[          #. replace any parts of the input
      R "\d+" "g"  #. matching /\d+/g
      +1           #. with its incremented form
    ]
    

    Mama Fun Roll

    Posted 2014-09-21T11:06:09.023

    Reputation: 7 234

    Is this answer non-competing? – Dennis – 2016-11-10T14:45:51.343

    oh rip :( I somehow thought this was a catalog question. – Mama Fun Roll – 2016-11-11T01:29:19.707

    0

    Gema, 14 characters

    <D>=@add{$1;1}
    

    Sample run:

    bash-4.3$ gema '<D>=@add{$1;1}' <<< 'teststring134this 123test string54 100'
    teststring135this 124test string55 101
    

    manatwork

    Posted 2014-09-21T11:06:09.023

    Reputation: 17 865

    0

    CJam, 18 bytes

    q_A,s-_:(:`ers~]:)
    

    Try it here.

    Explanation

    q         e# Read input.
    _A,s-     e# Duplicate and remove digits.
    _         e# Duplicate.
    :(:`      e# Decrement and get the string representation of each character.
    er        e# Map the characters to the decremented string representation.
    s~        e# Flatten to string and evaluate.
    ]:)       e# Wrap in an array and increment each element.
    

    jimmy23013

    Posted 2014-09-21T11:06:09.023

    Reputation: 34 042

    0

    R, 83 bytes

    Late to the party. Assumes input is stored in variable x. It's probably not needed to use regmatches to solve this but I couldn't figure out vectorized replacements without any external packages.

    paste0(el(r(x,m<-gregexpr("\\d+",x),T)),c(as.numeric(el(r(x,m)))+1,""),collapse="")
    

    Ungolfed and explained

    r=regmatches                                        # Alias for regmatch
    y=r(x<-scan(,""),m<-gregexpr("\\d+",x))             # return match digits
    i=r(x,m,T)                                          # return inverted match (non-digits)
    paste0(el(i),c(as.numeric(el(y))+1,""),collapse="") # join digits+1 and non-digits, element-wise
    

    Example output

    input: 
    "teststring135this 124test string55 101"
    
    output:
    [1] "teststring136this 125test string56 102"
    

    Billywob

    Posted 2014-09-21T11:06:09.023

    Reputation: 3 363