正则表达式将匹配字符串中最后出现的点 [英] RegEx that will match the last occurrence of dot in a string
问题描述
我有一个文件名,其中可以包含多个点,并且可以以任何扩展名结尾:
I have a filename that can have multiple dots in it and could end with any extension:
tro.lo.lo.lo.lo.lo.png
我需要使用正则表达式将点的最后一次出现替换为另一个字符串,例如@2x
,然后再次点(非常类似于视网膜图像文件名),即:
I need to use a regex to replace the last occurrence of the dot with another string like @2x
and then the dot again (very much like a retina image filename) i.e.:
tro.lo.png -> tro.lo@2x.png
这是我到目前为止所拥有的,但与任何内容都不匹配...
Here's what I have so far but it won't match anything...
str = "http://example.com/image.png";
str.replace(/.([^.]*)$/, " @2x.");
有什么建议吗?
推荐答案
您不需要正则表达式. String.lastIndexOf
即可.
You do not need a regex for this. String.lastIndexOf
will do.
var str = 'tro.lo.lo.lo.lo.lo.zip';
var i = str.lastIndexOf('.');
if (i != -1) {
str = str.substr(0, i) + "@2x" + str.substr(i);
}
查看实际效果 .
See it in action.
更新:正则表达式解决方案,仅出于乐趣:
Update: A regex solution, just for the fun of it:
str = str.replace(/\.(?=[^.]*$)/, "@2x.");
匹配文字点,然后断言((?=)
是正向超前)字符串末尾没有其他字符是点.替换项应包括一个匹配的点,除非您要删除它.
Matches a literal dot and then asserts ((?=)
is positive lookahead) that no other character up to the end of the string is a dot. The replacement should include the one dot that was matched, unless you want to remove it.
这篇关于正则表达式将匹配字符串中最后出现的点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!