gpt4 book ai didi

python - 单行注释的正则表达式

转载 作者:行者123 更新时间:2023-12-01 10:01:36 25 4
gpt4 key购买 nike

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

关于python - 单行注释的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15423658/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com