Solved

Python regular expression

Posted on 2009-05-05
14
419 Views
Last Modified: 2012-08-13
Hi all,

I have data like the following which I wish to process using a regular expression:

KEYWORD1 VARIABLE_1;
KEYWORD1 VARIABLE_2;
  KEYWORD2 VARIABLE_3;
 KEYWORD2 VARIABLE_4;

So i use the following:

temp1 = re.compile('\s*KEYWORD1\s+(\S+)')
temp2 = re.compile('\s*KEYWORD2\s+(\S+)')

Using this its straight forward to extract and store the VARIABLE_1 to VARIABLE_4, however I sometimes have the following structure

KEYWORD1 [1_OR_MORE_NUMBERS:0] VARIABLE_5;
KEYWORD1 [1_OR_MORE_NUMBERS:0] VARIABLE_6;

I can't seem to devise a regular expression that nicely extracts and stores all the variables - any thoughts?

0
Comment
Question by:trican
  • 5
  • 4
  • 2
  • +2
14 Comments
 
LVL 84

Expert Comment

by:ozo
ID: 24307020
do you want to skip over the  [1_OR_MORE_NUMBERS:0] or do you want to extract it together with the VARIABLE_5?
0
 
LVL 1

Author Comment

by:trican
ID: 24307031
Hi ozo,

I want to skip over [1_OR_MORE_NUMBERS:0]
0
 
LVL 41

Expert Comment

by:HonorGod
ID: 24307034
by 1 or more numbers, do you mean 1 or more digits?



temp1 = re.compile('\s*KEYWORD1\s+(\d+:0)?(\S+)')

Open in new window

0
 
LVL 1

Author Comment

by:trican
ID: 24307049
yes one or more digits
0
 
LVL 84

Expert Comment

by:ozo
ID: 24307060
to skip over things in [] you might use
'\s*KEYWORD2(?:\[.*?\]|\s)+(\S+)'
to get the last \S+ before the ; you might use
'\s*KEYWORD2\s.*?(\S+);'
0
 
LVL 41

Expert Comment

by:HonorGod
ID: 24307062
Are the square brackets actually there?
temp1 = re.compile('\s*KEYWORD1\s+(?\[\d+:0])?(\S+)')

Open in new window

0
 
LVL 1

Author Comment

by:trican
ID: 24307077
yes the square brackets are there
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 1

Author Comment

by:trican
ID: 24307167
still not quite working? I suspect its very close
0
 
LVL 84

Expert Comment

by:ozo
ID: 24307203
what is not working, and in what way is it not working?
0
 
LVL 84

Accepted Solution

by:
ozo earned 350 total points
ID: 24307230
\s*KEYWORD1\s+(?\[\d+:0])?(\S+)
may need another \s* in (\[\d+:0]\s*)?
0
 
LVL 9

Assisted Solution

by:ghostdog74
ghostdog74 earned 50 total points
ID: 24310875
the most straightforward way in Python, is not to use regular expression.

to store variables like you mentioned, use dictionaries (see code)

as for the second part

>>KEYWORD1 [1_OR_MORE_NUMBERS:0] VARIABLE_5;
>> KEYWORD1 [1_OR_MORE_NUMBERS:0] VARIABLE_6;

i don't know what you want to do with [1_OR_MORE_NUMBERS:0] so the solution doesn't take care of that.


d={}

for line in open("file"):

    line = line.strip().split()

    d[line[0]] = line[-1]

  

Open in new window

0
 
LVL 9

Expert Comment

by:ghostdog74
ID: 24310882
also, the check for KEYWORD in a string, use the "in" operator



for line in open("file"):

   if "KEYWORD" in line : # or if line.startswith("KEYWORD")

       #do something

Open in new window

0
 
LVL 1

Author Comment

by:trican
ID: 24311807
ozo,

I think  its workin ok now - I was confused that I could always use group(2) to access the information that I needed.  If you could explain why this work in this manner all the points are yours.

Also thanks ghostdog, whilst i agree not using regular epxressions is more readable I actually need the flexibility it gives.
0
 
LVL 28

Assisted Solution

by:pepr
pepr earned 100 total points
ID: 24314775
See http://docs.python.org/library/re.html#regular-expression-syntax

The (?:anything) should consider "anything" without creating a group. There should be the colon; otherwise, it is buggy.

Pay attention that you should use r'raw strings' for regular expression pattern literals. Alternatively, you must double the backslashes.

You can also name the group. See the examples below. It produces the following output on my computer:

C:\tmp\___python\trican>a.py
('VARIABLE_6',)
('[12345:0]', 'VARIABLE_6')
('[12345:0]', 'VARIABLE_6')
{'var': 'VARIABLE_6', 'num': '[12345:0]'}
VARIABLE_6
import re
 

s = 'KEYWORD1 [12345:0] VARIABLE_6;'
 

rex = re.compile(r'\s*KEYWORD1\s+(?:\[\d+:0])?\s*(\S+);\s*')

m = rex.search(s)

print m.groups()
 

rex = re.compile(r'\s*KEYWORD1\s+(\[\d+:0])?\s*(\S+);\s*')

m = rex.search(s)

print m.groups()
 

rex = re.compile(r'\s*KEYWORD1\s+(?P<num>\[\d+:0])?\s*(?P<var>\S+);\s*')

m = rex.search(s)

print m.groups()

print m.groupdict()

print m.group('var')

Open in new window

0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Does the idea of dealing with bits scare or confuse you? Does it seem like a waste of time in an age where we all have terabytes of storage? If so, you're missing out on one of the core tools in every professional programmer's toolbox. Learn how to …
If you’re thinking to yourself “That description sounds a lot like two people doing the work that one could accomplish,” you’re not alone.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now