栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

单行注释的正则表达式

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

单行注释的正则表达式

用于匹配单行注释的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))


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/634268.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号