单行注释的正则表达式

时间:2013-03-15 02:21:40

标签: python regex

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

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

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

2 个答案:

答案 0 :(得分:3)

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

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

这是一个针对模式运行一堆测试字符串的小脚本。

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))

答案 1 :(得分:2)

我认为这有效(使用pyparsing):

data = """
class HelloWorld {

    // method main(): ALWAYS the APPLICATION entry point
    public static void main (String[] args) {
        System.out.println("Hello World!"); // Nested //Print 'Hello World!'
        System.out.println("http://www.example.com"); // Another nested // Print a URL
        System.out.println("\"http://www.example.com"); // A nested escaped quote // Print another URL
    }
}"""


from pyparsing import *
from pprint import pprint
dbls = QuotedString('"', '\\', '"')
sgls = QuotedString("'", '\\', "'")
strings = dbls | sgls
pprint(dblSlashComment.ignore(strings).searchString(data).asList())

[['// method main(): ALWAYS the APPLICATION entry point'],
 ["// Nested //Print 'Hello World!'"],
 ['// Another nested // Print a URL'],
 ['// A nested escaped quote // Print another URL']]

如果您有/* ... */个样式的评论,恰好有单行注释,并且实际上并不想要那些,那么您可以使用:

pprint(dblSlashComment.ignore(strings | cStyleComment).searchString(data).asList())

http://chat.stackoverflow.com/rooms/26267/discussion-between-nhahtdh-and-martega 中讨论)