单行 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())
.*
而不是.~
? - Explosion Pills/*..我也是单行的...*/
也算单行注释吗? - Kentre.match()
锚定在输入字符串的开头(如果我没记错,它需要整个字符串与RE匹配),因此您的第二个RE将无法匹配,例如'some code; // comment'
。点击这里。 - millimoose