什么是单行 java 注释的正则表达式:我正在尝试以下语法:
def single_comment(t):
r'\/\/.~(\n)'
#r'//.*$'
pass
但是,我无法忽略单行注释我该怎么做?
用于匹配单行注释的 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))
我认为这有效(使用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中所述)