Kon*_*sta 6 python regex ply lexical-analysis
我正在做一个词法分析器作为大学课程的一部分。我们教授给我们的脑筋急转弯之一(对评分没有贡献的额外作业)是我们如何在字符串文字中实现注释。
我们的字符串文字以感叹号开始和结束。例如!this is a string literal!
我们的评论以三个句点开始和结束。例如...This is a comment...
从字符串文字中删除注释相对简单。只需通过匹配字符串文字/!.*!/并通过正则表达式删除注释即可。如果连续的逗号超过三个,但没有结尾的逗号,则抛出错误。
但是,我想更进一步。我想在字符串文字中实现感叹号的转义。不幸的是,我似乎无法同时使用注释和感叹号转义。
我想要创建的是可以包含注释和感叹号转义的字符串文字。这怎么可能?
例子:
!Normal string!
!String with escaped \! exclamation mark!
!String with a comment ... comment ...!
!String \! with both ... comments can have unescaped exclamation marks!!!... !
Run Code Online (Sandbox Code Playgroud)
这是我当前的代码,不能忽略注释中的感叹号:
!Normal string!
!String with escaped \! exclamation mark!
!String with a comment ... comment ...!
!String \! with both ... comments can have unescaped exclamation marks!!!... !
Run Code Online (Sandbox Code Playgroud)
查看此正则表达式以匹配字符串文字: https: //regex101.com/r/v2bjWi/2。
(?<!\\)!(?:\\!|(?:\.\.\.(?P<comment>.*?)\.\.\.)|[^!])*?(?<!\\)!。
(?<!\\)!意义未转义的感叹号包围,\\!、注释(?:\.\.\.(?P<comment>.*?)\.\.\.)和非感叹号组成[^!]。请注意,这大约是使用正则表达式所能实现的最大程度。任何额外的要求,都将不再足够。| 归档时间: |
|
| 查看次数: |
178 次 |
| 最近记录: |