我想提取像这样的CSS文件的第一个注释块:

/*
author : name
uri : link
etc
*/

不提取其他评论

/* header */
/* footer */

所以我尝试了:

print re.findall(r'\/\*(.*)\*\/', cssText )

这给了我所有其他评论,除了我需要的块。因此,我将其更改为更精确:

print re.findall(r'\/\*\n(.*)^\*\/', cssText )

结果一无所有:

[]

你有建议吗?谢谢 :-)

有帮助吗?

解决方案 3

你可以这样做:

css = """
/*
author : name
uri : link
etc
*/

bla bla bla. Blah blah
x: 10;
color: red;

/* header */
/* footer */
"""

import re

pat = r'\/\*([\S\s]*?)\*\/'

print re.findall(pat, css)
print re.search(pat, css).group()

其他提示

如果您只需要第一个评论,则只能使用第一个结果:

print re.findall(r'\/\*(.*)\*\/', cssText )[0]

您也可以使用 re.search 哪个搜索第一个匹配发生:

print re.search(r'\/\*(.*)\*\/', cssText )

当您匹配多行字符串时,您需要制作。匹配 n也:

print re.findall(r'\/\*\n(.*?)\*\/', cssText, re.S)

看:http://docs.python.org/2/library/re.html#re.s

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top