Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

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

I'm working on an open source project that needs it's copyright headers brought up to date. Currently every file contains a commented header with various years. Some correctly say 2015, others say anything from 2011 to 2014 and some provide a date range (i.e. 2011-2014 - see example included).

I would like to programmatically change all out of date years to read as 2015. Is it possible to find and replace the second year only? I'm currently using this as my regex to grab each header:

/*(?:(?!*/).|[

])**/

And here is a sample header:

 /**
 * 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]"
 */
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As per @stribizhev's comment(s)

If you want to replace:

  • 2011-2014 turns into 2011-2015
  • 2014 turns into 2015
  • 2011 to 2014 turns into 2011 to 2015
  • And possibly more (if you're not careful)

then you could use:

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

This is not a very narrow regex as it could replace more than what is expected.

I recommend testing this out in an online regex tester first.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...