[英]Using regex to to replace only if the string filename has .jpg or .png extension
I have a huge filename string list, using the regex to to replace only if the string filename has .jpg or .png extension我有一个巨大的文件名字符串列表,仅当字符串文件名具有 .jpg 或 .png 扩展名时才使用正则表达式替换
Means to say if the filename is表示文件名是否为
Scene.jpg
then expected result is IMG_Scene.jpg
. Scene.jpg
那么预期的结果是IMG_Scene.jpg
。
Scenejpgx.docx
then expected result is Scenejpgx.docx
itself Scenejpgx.docx
那么预期的结果是Scenejpgx.docx
本身
I tried with我试过
str.replace(/^/i,"IMG_");
but this replaces every strings.但这会替换每个字符串。
You can use您可以使用
.replace(/.*\.(?:jpg|png)$/i, 'IMG_$&')
See the regex demo查看正则表达式演示
Details细节
.*
- any zero or more chars other than line break chars as many as possible .*
- 尽可能多的除换行符以外的零个或多个字符\\.
- a dot (?:jpg|png)
- jpg
or png
(?:jpg|png)
- jpg
或png
$
- end of string. $
- 字符串的结尾。 The $&
is the backreference to the whole match, so IMG_$&
basically prepends the match with IMG_
. $&
是对整个匹配项的反向引用,因此IMG_$&
基本上在匹配项之前加上IMG_
。
See JavaScript demo:参见 JavaScript 演示:
const strings = ['Scene.jpg','Scenejpgx.docx']; const re = /.*\\.(?:jpg|png)$/i; strings.forEach( x => console.log(x, '=>', x.replace(re, 'IMG_$&')) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.