【发布时间】:2014-06-16 12:49:02
【问题描述】:
我对正则表达式一无所知。
如何使用正则表达式更改文件名
我想将文件名从 'style-dist.css' 更改为 style.css
【问题讨论】:
-
为什么要使用正则表达式?而是可以直接用 string.Replace 方法替换。
-
它是 gruntfile.js 副本的一部分 - 我想复制一个文件但更改文件名
我对正则表达式一无所知。
如何使用正则表达式更改文件名
我想将文件名从 'style-dist.css' 更改为 style.css
【问题讨论】:
如果您可以在尝试匹配/更改的字符串中找到模式,则正则表达式可以工作。例如,在这里您只给出了一个字符串。我假设您正在尝试从中删除“-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/
【讨论】:
如果使用 grunt,则需要在 gruntfile 中使用 rename 属性。
您可以在building file objects dynamically 上的 grunt 文档中找到更多信息。
你可以设置你的 gruntfile 看起来像这样。
代码:
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/, '');
}
}
【讨论】: