使用正则表达式更改文件名

时间:2014-06-16 12:49:02

标签: regex gruntjs

我对正则表达式一无所知。

如何使用正则表达式更改文件名

我想将文件名从'style-dist.css'更改为style.css

2 个答案:

答案 0 :(得分:1)

如果您可以在要匹配/更改的字符串中找到模式,则可以使用正则表达式。例如,在这里你只给了一个字符串。我假设你试图从中删除'-dist'部分?如果还有其他模式,请在你的问题中告知。

可以通过

完成
new_name = old_name.replace(/-dist/, '');

然而,如果你不知道正则表达式,并且有一些时间,我建议你的脚湿透了。尽你所能地。以下是一些介绍性文章:

http://gnosis.cx/publish/programming/regular_expressions.html

http://www.javascriptkit.com/javatutors/re.shtml

这是一本更完整的书(在线): http://regex.learncodethehardway.org/book/

答案 1 :(得分:0)

如果使用grunt,则需要使用gruntfile中的rename属性。

您可以在building file objects dynamically上的grunt文档中找到更多信息。

你可以设置你的gruntfile看起来像这样。

  • 请注意,您必须将此工作添加到您的设置中,以便所有内容排列/等等。
  • 请注意,此处没有其他护栏......没有错误检查等。
  • 请注意,您需要计算src和dest位置的globs
  • 请注意,如果您使用多个正则表达式模式执行此操作,或者您的通配模式变得非常复杂,这很快就会变成一场噩梦,并且可能会找到另一种方法来执行此操作。

代码:

copy: {
    main: {
      files: [
        {
          expand: true, 
          cwd: '<whatever your cwd is>', 
          src: ['<glob for your -dist.js file location>'], 
          dest: '<glob for a PATH..a PATH>', 
          rename: function(dest, src) {    
            // receives the dest PATH and src and then
            // takes the dest path, appends the modified src using the regex
            return dest + src.replace(/-dist/, '');
         }
       }