正则表达式不在pycharm中工作

时间:2016-04-18 14:09:42

标签: python regex

我需要找到所有匹配并删除它们,假设我需要删除两行中定义的宏:

#define something \
void single(double * state, char ch);

我得到了这个正则表达式:#.*\n.*,它正在pyregex.com和pythex.com上工作但不在我的代码中:

myFile = re.sub('#.*\n.*',"", myFile, count=0, flags=0)

我甚至试过了r"""#.*\\\n.*""",但没有一个可以使用

2 个答案:

答案 0 :(得分:1)

尝试编译正则表达式以匹配多行字符串:

myFile = re.sub(re.compile('#.*\n.*', re.MULTILINE),"", myFile, count=0, flags=0)

假设您从名为/tmp/macro.txt的文件中获取字符串,此程序将匹配并删除所有内容:

import re

f = open('/tmp/macro.txt', 'r')
content = f.read()
print('old content:'+content)
new_content = re.sub(re.compile('#.*\n.*', re.MULTILINE),"", '/tmp/tst.tst', count=0, flags=0)

print('new content:'+new_content)

即使是第二个之后的行 - 正则表达式需要更新以避免这种情况。 我用于测试的/tmp/macros.txt文件是:

#define somenthing \
void single(double * state, char ch);

aaaaaaaaa
aaaaaaaa

如果您的字符串是在本地定义的(在您的python程序中),您自己说当打印它时没有新行,因此寻找新行的正则表达式将不匹配。

在这种情况下匹配的是一个以#开头的字符串,如下所示:

>>> import re
>>> str="""#define something \
... void single(double * state, char ch);"""
>>> myFile = re.sub('^#.*',"", str, count=0, flags=0)
>>> myFile
''
>>> str
'#define something void single(double * state, char ch);'
>>> 

答案 1 :(得分:0)

尝试以下

In [78]: s = """#define something \
....: void single(double * state, char ch);
....: /*something else*/"""

In [97]: re.sub(r"#.*?\n","", s)
Out[97]: '/*something else*/'

请评论是否有效。