23

I'm having to parse a text dump of a spreadsheet. I have a regular expression that correctly parses each line of the data, but it's rather long. It's basically just matching a certain pattern 12 or 13 times.

The pattern I want to repeat is

\s+(\w*\.*\w*);

This is the regular expression (shortened)

^\s+(\w*\.*\w*);\s+(\w*\.*\w*);\s+(\w*\.*\w*);\s+(\w*\.*\w*);\s+(\w*\.*\w*);\s+(\w*\.*\w*);

Is there a way to match a pattern a set number of times without copy pasting like this? Each of those sections correspond to data columns, all of which I need. I'm using Python by the way. Thanks!

Joe Lyga
  • 663
  • 2
  • 5
  • 17

2 Answers2

61

(\s+(\w*\.*\w*);){12}

The {n} is a "repeat n times"

if you want "12 - 13" times,

(\s+(\w*\.*\w*);){12,13}

if you want "12+" times,

(\s+(\w*\.*\w*);){12,}

joe_coolish
  • 7,161
  • 13
  • 61
  • 109
6

How about using:

[x.group() for x in re.finditer(r'(\s+(\w*\.*\w*);)*', text)]

Did you find the findall method yet? Or consider splitting at ;?

map(lambda x: x.strip(), s.split(";"))

is probably what you really want.

Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
Has QUIT--Anony-Mousse
  • 73,503
  • 12
  • 131
  • 189
  • Ah, that's a great idea. Splitting at semicolon is much simpler. All I would need to do is remove the whitespace. Thanks! – Joe Lyga Jan 12 '12 at 23:24