Question: I have a string, and i need to check whether it contains a `number/digit at the end` of the string, and need to increment that `number/digit` at the end of the string with `+1` 

I will get the strings as below

```
string2  = suppose_name_1
string3  = suppose_name_22
string4  = supp22ose45_na56me_45

```

for sure i will get the string in the above format like suppose\_somthing + `Underscore` + `digits`

So from the above strings 

1. I need to check whether a string contains a number/digit at the end of the string after underscore
2. If it contains then need to increment that with `+1` like below

string2 = suppose\_name\_**2**

string3 = suppose\_name\_**23**

string4 = supp22ose45\_na56me\_**46**

How can we do this in python by using regular expressions or something, but that should be very fast.

I have done something like [here](https://stackoverflow.com/questions/11232474/is-there-a-better-way-to-find-if-string-contains-digits), but want to implement with re that will be very fast , so approached SO

`Edit:` 
sorry din't mentioned above

Sometimes it contains just `something_name` without integer, hence i need to check whether it contains a number in it first

Answer: 
How about using regular expressions:

```
import re

def process_string(s):
    try:
        part1, part2 = re.search('^(.*_)(\d+)$', s).groups()
        part2 = str(int(part2) + 1)
        return part1 + part2 
    except AttributeError:
        return s

print process_string("suppose_name_1")
print process_string("suppose_name_22")
print process_string("supp22ose45_na56me_45")

print process_string("suppose_name")

```

prints:

```
suppose_name_2
suppose_name_23
supp22ose45_na56me_46
suppose_name

```

FYI, there is nothing wrong or scary with using regular expressions.
Here's short regex solution that increments the number with re.sub(...):

```
from re import sub

string2  = 'suppose_name_1'
string3  = 'suppose_name_22'
string4  = 'supp22ose45_na56me_45'
print [sub(r'^(?P<pretext>.*_)(?P<number>\d+)$', lambda x : '%s%d' % (x.group('pretext'), int(x.group('number')) + 1), s) for s in (string2, string3, string4)]

```

and the output:

```
['suppose_name_2', 'suppose_name_23', 'supp22ose45_na56me_46']

```

The easier to read version would be something like this:

```
from re import sub

string2  = 'suppose_name_1'
string3  = 'suppose_name_22'
string4  = 'supp22ose45_na56me_45'
regex = r'^(?P<pretext>.*_)(?P<number>\d+)$'

def increment(matchObject):
    return '%s%d' % (matchObject.group('pretext'), int(matchObject.group('number')) + 1)

for s in (string2, string3, string4):
    print sub(regex, increment, s)

```

and the output:

```
suppose_name_2
suppose_name_23
supp22ose45_na56me_46

```