单行注释的正则表达式

3
单行 Java 注释的正则表达式是什么? 我正在尝试下面的语法:
     def single_comment(t):
          r'\/\/.~(\n)'
          #r'//.*$'
          pass

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


你是不是想说 .* 而不是 .~ - Explosion Pills
1
不要忘记使用正则表达式!:P - Mark Rushakoff
这个 /*..我也是单行的...*/ 也算单行注释吗? - Kent
你要匹配哪个输入字符串,并使用哪种方法?默认情况下,re.match()锚定在输入字符串的开头(如果我没记错,它需要整个字符串与RE匹配),因此您的第二个RE将无法匹配,例如 'some code; // comment'点击这里 - millimoose
你似乎正在使用原始字符串,但仍在转义斜杠? - Moshe
显示剩余2条评论
2个回答

4

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

非常抱歉,你说得完全正确。一开始我并没有认真考虑它,因为它看起来很简单。但是在更深入地思考后,我发现它比我想象的要复杂得多。不过,我已经更新了我的解决方案,并加入了一些处理一般情况的内容。 - martega
你可以查看我和Mike的讨论来检查你的答案。我认为它无法处理一般情况。 - nhahtdh
你能给我一个不通过的案例吗? - martega
让我们在聊天中继续这个讨论:http://chat.stackoverflow.com/rooms/26267/discussion-between-nhahtdh-and-martega - nhahtdh
1
谢谢,这是整个互联网上最好的答案。 - Avo Asatryan
显示剩余2条评论

3

我认为这个方法能够奏效(使用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())

(如在https://chat.stackoverflow.com/rooms/26267/discussion-between-nhahtdh-and-martega中所讨论的那样)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接