单行注释的正则表达式 [英] Regular Expression for single line comments

查看:40
本文介绍了单行注释的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

单行java注释的正则表达式是什么:我正在尝试以下语法:

What is the regular expression for single line java comments: I am trying the following grammar :

     def single_comment(t):
          r'\/\/.~(\n)'
          #r'//.*$'
          pass

但是,我无法忽略单行注释,我该怎么办?

but, I am unable to ignore the single line comments how can I do it?

推荐答案

用于匹配单行注释的 Python 正则表达式(仅匹配以//开头的注释,不匹配/* */).不幸的是,这个正则表达式非常难看,因为它必须考虑字符串中的转义字符和//.如果您在实际代码中需要它,您应该找到一个更容易理解的解决方案.

Python regular expression for matching single line comments (only matches comments that start with //, not /* */). Unfortunately, this regular expression is pretty ugly as it has to account for escaped characters and // within strings. You should find a more easily understandable solution if you ever need this in real code.

import re
pattern = re.compile(r'^(?:[^"/\\]|\"(?:[^\"\\]|\\.)*\"|/(?:[^/"\\]|\\.)|/\"(?:[^\"\\]|\\.)*\"|\\.)*//(.*)$')

这是一个小脚本,它根据模式运行一堆测试字符串.

This is a little script that runs a bunch of test strings against the pattern.

import re

pattern = re.compile(r'^(?:[^"/\\]|\"(?:[^\"\\]|\\.)*\"|/(?:[^/"\\]|\\.)|/\"(?:[^\"\\]|\\.)*\"|\\.)*//(.*)$')

tests = [
    (r'// hello world', True),
    (r'     // hello world', True),
    (r'hello world', False),
    (r'System.out.println("Hello, World!\n"); // prints hello world', True),
    (r'String url = "http://www.example.com"', False),
    (r'// hello world', True),
    (r'//\\', True),
    (r'// "some comment"', True),
    (r'new URI("http://www.google.com")', False),
    (r'System.out.println("Escaped quote\""); // Comment', True)
]

tests_passed = 0

for test in tests:
    match = pattern.match(test[0])
    has_comment = match != None
    if has_comment == test[1]:
        tests_passed += 1

print "Passed {0}/{1} tests".format(tests_passed, len(tests))

这篇关于单行注释的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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