字符串中的注释和注释中的字符串 [英] Comments in string and strings in comments

查看:39
本文介绍了字符串中的注释和注释中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Python 和 Regex 计算 C 代码中包含的注释中的字符数,但没有成功.我可以先删除字符串以删除字符串中的注释,但这也会删除注释中的字符串,结果会很糟糕.是否有机会通过使用正则表达式来不匹配注释中的字符串,反之亦然?

I am trying to count characters in comments included in C code using Python and Regex, but no success. I can erase strings first to get rid of comments in strings, but this will erase string in comments too and result will be bad ofc. Is there any chance to ask by using regex to not match strings in comments or vice versa?

推荐答案

不,不是真的.

正则表达式不是解析您所描述的嵌套结构的正确工具;相反,您将需要解析 C 语法(或您感兴趣的哑子子集"),并且您可能会发现正则表达式对此很有帮助.一个相对简单的具有三个状态(CODE、STRING、COMMENT)的状态机就可以做到.

Regex is not the correct tool to parse nested structures like you describe; instead you will need to parse the C syntax (or the "dumb subset" of it you're interested in, anyway), and you might find regex helpful in that. A relatively simple state machine with three states (CODE, STRING, COMMENT) would do it.

这篇关于字符串中的注释和注释中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆