python正则表达式查找跨越多行的多行C注释

标签 python ply

我正在尝试获得一个适用于多行 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/

相关文章:

python - 如何计算两个不同列表之间的共享元素? (Python)

python - 如何创建用于识别 CR 的层规则?

python - 如何为手写词法分析器编写 PLY 接口(interface)?

python-2.7 - 使用 PLY 匹配普通字符串

python - 确定第 15 天后滚动到下个月的当前月份变量 - python 2.7

python - 从 Python 执行存储过程

python - 以第一个字母为行并保留为列来旋转列表

带转义单引号的单引号字符串上的 Python 正则表达式

Python PLY 赋值操作失败

python - 如何解决 "iterator should return strings, not bytes"