如果存在特定字符集,編寫正則表達式以跳過一行?

[英]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 :-

我試圖在python中編寫一個正則表達式來解析一個包含這樣內容的文件: -

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.

其中fileContents將文件數據作為字符串。

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

但是這個正則表達式甚至匹配注釋(行與//)行。如何避免匹配注釋行。

3 个解决方案

#1


1  

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)

#2


2  

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是任何空格字符

\S is any non-space character

\ S是任何非空格字符

#3


0  

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

如果你正在解析C代碼,你可以使用像pycparser這樣的東西。正則表達式不適合(或可能)解析任何編程語言。

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/10/05/2f775c8a238963d76cd254f8c2bda14b.html



 
  © 2014-2022 ITdaan.com 联系我们: