我正在尝试获得一个适用于多行 C 注释的正则表达式。设法使其适用于/* comments here */但如果评论转到下一行则不起作用。如何制作跨越多行的正则表达式?
使用这个作为我的输入:
/* 这条评论
必须承认 */
我遇到的问题是“must, be and recognized”匹配为 ID 和 */作为非法字符。
#!/usr/bin/python
import ply.lex as lex
tokens = ['ID', 'COMMENT']
t_ID = r'[a-zA-Z_][a-zA-Z0-9_]*'
def t_COMMENT(t):
r'(?s)/\*(.*?).?(\*/)'
#r'(?s)/\*(.*?).?(\*/)' does not work either.
return t
# Error handling rule
def t_error(t):
print("Illegal character '%s'" % t.value[0])
t.lexer.skip(1)
lex.lex() #Build the lexer
lex.input('/* this comment\r\n must be recognised */\r\n')
while True:
tok = lex.token()
if not tok:break
if tok.type == 'COMMENT':
print tok.type
我尝试了很多:Create array of regex match(multiline)和 How to handle multiple rules for one token with PLY以及 http://www.dabeaz.com/ply/ply.html 提供的其他一些东西
最佳答案
当我想在 C 中查找多行注释时,我使用这个正则表达式:
如果我想包含 '/* */' 字符:
\/\*(\*(?!\/)|[^*])*\*\/
如果我不想包含它:
(?<=\*)[\n]*.*[\n]*.*[\n]*[\n]*?[\n]*(?=\*)
关于python正则表达式查找跨越多行的多行C注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32453628/