用于匹配单行注释的Python正则表达式(仅匹配以//开头的注释,而不是/ * *
/的注释)。不幸的是,此正则表达式非常丑陋,因为它必须考虑转义字符和//字符串中的字符。如果您需要真实的代码,则应该找到一个更容易理解的解决方案。
import repattern = re.compile(r'^(?:[^"/\]|"(?:[^"\]|\.)*"|/(?:[^/"\]|\.)|/"(?:[^"\]|\.)*"|\.)*//(.*)$')
这是一个小脚本,针对该模式运行一堆测试字符串。
import repattern = 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 = 0for test in tests: match = pattern.match(test[0]) has_comment = match != None if has_comment == test[1]: tests_passed += 1print "Passed {0}/{1} tests".format(tests_passed, len(tests))


