Kassandra
Kassandra

Reputation: 301

Python regex or split/strip to get int from between brackets in line of text

I have a text file with lines like this:

[00451] Kayle - 2/3/15 - Win - 2012-11-22

the number between the brackets [ ] at the start is an id number, I need to get that from the last line of the file (or a string passed containing that line) so I can increment it for writing more lines to the file so every game record will have a unique id number. I've been trying for a while with split, strip, and regex, but I can't seem to get it to work. Can anyone help? I could just use lines of the file to do this maybe but I wanted to be able to re-sort the file later on by id, name, or other criteria.

My data written to the file in my other code looks like this:

data = "[%s] %s - %s/%s/%s - %s - %s\n" % (id, champname, kills, deaths, assists, winloss, timestamp)

How can I get the id of the last line so I can increment future appends id?

Upvotes: 1

Views: 3641

Answers (2)

avasal
avasal

Reputation: 14854

you can get the data from the line like this,,

In [5]: x = "[00451] Kayle - 2/3/15 - Win - 2012-11-22"

In [6]: x.split(']')[0].lstrip('[')
Out[6]: '00451'

then convert it to int and do the mathematics

In [7]: str(int(x.split(']')[0].lstrip('[')) + 1).zfill(5)
Out[7]: '00452'

another method to do this could be

In [8]: id = "%05d" %(int(x.split(']')[0].lstrip('[')) + 1)

In [9]: id
Out[9]: '00452'

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 838356

Here's a regular expression solution:

>>> s = '[00451] Kayle - 2/3/15 - Win - 2012-11-22'

>>> import re
>>> re.match(r'\[(\d+)\]', s).group(1)
00451

Upvotes: 1

Related Questions