使用JavaScript regex以编程方式更改所有文件头中的版权年份

Using JavaScript regex to programmatically change the copyright year in header of all files

本文关键字:文件 regex JavaScript 编程 方式更 使用      更新时间:2023-09-26

我正在做一个开源项目,需要更新它的版权头。目前,每个文件都包含一个带有不同年份的注释头。有些正确地说是2015年,有些说是2011年到2014年之间的任何时间,有些则提供了一个日期范围(即2011-2014 -参见附带的示例)。

我想通过编程将所有过期年份更改为2015年。是否有可能只找到并替换第二年的学生?我目前使用这个作为我的正则表达式来抓取每个头:

'/'*(?:(?!'*'/).|['n'r])*'*'/

下面是一个示例标题:

 /**
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2011-2013 Company Name AS. All rights reserved.
 *
 * The contents of this file are subject to the terms
 * of the Common Development and Distribution License
 * (the License). You may not use this file except in
 * compliance with the License.
 *
 * You can obtain a copy of the License at
 * http://someurl.com
 * See the License for the specific language governing
 * permission and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL
 * Header Notice in each file and include the License file
 * at http://someurl.com/license.html
 * If applicable, add the following below the CDDL Header,
 * with the fields enclosed by brackets [] replaced by
 * your own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 */

根据@stribizhev的评论

如果你想替换:

  • 2011-2014变为2011-2015
  • 2014变为2015
  • 2011 to 2014变为2011 to 2015
  • 可能更多(如果你不小心)

那么你可以使用:

.replace(/('/'*(?:(?!'*'/)[^])*)'b(-?'d{4} )'b/, "$12015 ")

这不是一个非常狭窄的正则表达式,因为它可以替换比预期更多的内容。

我建议先在一个在线正则表达式测试器中测试一下。