frazman
frazman

Reputation: 33243

extracting regular expression from string

Is, there a better way to extract the strings :

  'Found 1 items\ndrwxr-xr-x   - hadoop supergroup          0 2013-02-16 13:21 /user/hadoop/wiki\n'

All the strings will be like:

  'Found **n** items\n**permissions**   - **username** **group**          **notsurewhatthisis** **date** **time** **folders(or file)**\n'

Right now.. i am splitting it as:

line = line.split()
num_items = int(line[1])
permissions = line[3]

etc..

So basically this is a no brainer solution..

Trying to see if there is a "python" way to do this.

Upvotes: 0

Views: 65

Answers (1)

eyquem
eyquem

Reputation: 27575

ss = ('Found 1 items\n'
      "drwxr-xr-x   - hadoop supergroup          "
      '0 2013-02-16 13:21 /user/hadoop/wiki\n')

('Found **n** items\n'
 '**permissions**   - **username** **group**          '
 '**notsurewhatthisis** **date** **time** **folders(or file)**\n')

import re

r = re.compile('Found +(\d+) +items *\n *(.+?) *- ')

print r.search(ss).groups()

ss is a string
'Found +(\d+) +items *\n *(.+?) *- ' is a string used as a pattern for creating a regular expression object
r is the regular expression, an object which is not a string

Upvotes: 2

Related Questions