gpt4 book ai didi

注释代码中的 Python 正则表达式

转载 作者:太空宇宙 更新时间:2023-11-03 15:57:27 25 4
gpt4 key购买 nike

我试图在大多数文件开头的注释代码中匹配开源许可证类型。但是,对于所需字符串(例如较小的通用公共(public)许可证)跨越两行的情况,我遇到了困难。例如,请参阅许可证下面的代码。

 * Copyright (c) Codice Foundation
* <p/>
* This is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser
* General Public License as published by the Free Software Foundation, either version 3 of the
* License, or any later version.
* <p/>
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. A copy of the GNU Lesser General Public License
* is distributed along with this program and can be found at
* <http://www.gnu.org/licenses/lgpl.html>.
*/

由于注释代码中的空格数量未知以及不同语言中的注释字符不同,因此无法使用正则表达式回溯。我当前的正则表达式示例如下:

self._cr_license_re['GNU']                            = re.compile('\sGNU\D')
self._cr_license_re['MIT License'] = re.compile('MIT License|Licensed MIT|\sMIT\D')
self._cr_license_re['OpenSceneGraph Public License'] = re.compile('OpenSceneGraph Public License', re.IGNORECASE)
self._cr_license_re['Artistic License'] = re.compile('Artistic License', re.IGNORECASE)
self._cr_license_re['LGPL'] = re.compile('\sLGPL\s|Lesser General Public License', re.IGNORECASE)
self._cr_license_re['BSD'] = re.compile('\sBSD\D')
self._cr_license_re['Unspecified OS'] = re.compile('free of charge', re.IGNORECASE)
self._cr_license_re['GPL'] = re.compile('\sGPL\D|(?<!Lesser)\sGeneral Public License', re.IGNORECASE)
self._cr_license_re['Apache License'] = re.compile('Apache License', re.IGNORECASE)
self._cr_license_re['Creative Commons'] = re.compile('\sCC\D')

我欢迎任何有关如何在 python 中使用正则表达式解决此问题的建议。

最佳答案

您可以使用this regex并替换为空格

\s*\*\s*\/?

这应该将多行注释放在一行上,然后您可以在其中找到许可证。

关于注释代码中的 Python 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40665066/

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