deovrat singh
deovrat singh

Reputation: 1215

Writing regular expression to skip a line if specific set of characters are present?

I am trying to write a regex in python to parse a file having contents like this :-

static const PropertyID PROPERTY_X = 10225;
//static const PropertyID PROPERTY_Y = 10226;
   //static const PropertyID PROPERTY_Z = 10227;

I want to extract the property name and number for only non commented properties. This is the expression I wrote

tuples = re.findall(r"[^/]*static[ \t]*const[ \t]*PropertyID[ \t]*(\w+)[ \t]*=[ \t]*(\d+).*",fileContents)

where fileContents has the data of file as string.

But this regex is even matching the commented(lines with //) lines. How to make it avoid matching the commented lines.

Upvotes: 0

Views: 1326

Answers (3)

Ehtesh Choudhury
Ehtesh Choudhury

Reputation: 7790

If you're parsing C code, you can use something like pycparser. Regular expressions aren't suited (or possible) to parse any programming language.

Alternatively, I think this code is simpler for what you're doing:

import re
string = "   //static const PropertyID PROPERTY_Z = 10227;"
results = re.split("\s*",string)
#results = ['//static', 'const', 'PropertyID', 'PROPERTY_Z', '=', '10227;']

if results[0].startswith("\\") or results[0].startswith("/*"):
    pass

Upvotes: 0

Andrea Spadaccini
Andrea Spadaccini

Reputation: 12651

You could specify that, after the start of the line, you only want spaces before the first static:

tuples = re.findall(r"^\s*static[ \t]*const[ \t]*PropertyID[ \t]*(\w+)[ \t]*=[ \t]*(\d+).*",fileContents)

Upvotes: 1

Asmor
Asmor

Reputation: 5181

Try:

r"(?m)^(?!//)static\s+const\s+PropertyID\s+(\S+)\s+=\s+(\d+);"

A couple notes.

^ matches beginning of line

(?!//) is a negative lookahead, asserting that it is NOT followed by //

\s is any space character

\S is any non-space character

Upvotes: 2

Related Questions