regex 用于选择\* ....和.... *\ [duplicate]之间的任何内容的正则表达式

ttygqcqt  于 2023-01-27  发布在  其他
关注(0)|答案(1)|浏览(72)
    • 此问题在此处已有答案**:

Regex to match a C-style multiline comment(8个答案)
18小时前关门了。
我想为多行注解写一个正则表达式。
我的表情:\\*[\s\S]*?\*\/
我的期望:
(一)

/* 

this is a comment

*/

Not a comment 

/*

new comment

*/
/*
comment 1
comment 3
*/
Not a comment
Not a comment
*/

我得到的输出:
1.

8yparm6h

8yparm6h1#

你的RegEx匹配了错误类型的斜杠。\\*被从头到尾解析,所以\\被解释为\的转义序列,这样*字符就没有转义。要解决这个问题,使用\/\*来启动你的RegEx,或者在Python中使用/\*和一个原始字符串。如下所示:

import re

test1 = '''
/*

this is a comment

*/

Not a comment 

/*

new comment

*/
'''

test2 = '''
/*
comment 1
comment 3
*/
Not a comment
Not a comment
*/
'''

# out1 = re.findall(r'/\*.*?\*/', test1)
out1 = re.findall(r'/\*([\s\S]*?)\*\/', test1)
print(out1)

out2 = re.findall(r'/\*([\s\S]*?)\*\/', test2)
print(out2)

相关问题