Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 

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 -> [email protected] 

Here's what I have so far but it won't match anything...

str = "http://example.com/image.png"; str.replace(/.([^.]*)$/, " @2x."); 

any suggestions?

like image 447
alt Avatar asked Jun 21 '12 08:06

alt


People also ask

How do you match a dot in regex?

in regex is a metacharacter, it is used to match any character. To match a literal dot in a raw Python string ( r"" or r'' ), you need to escape it, so r"\." Unless the regular expression is stored inside a regular python string, in which case you need to use a double \ ( \\ ) instead.

Does regex match dot space?

Yes, the dot regex matches whitespace characters when using Python's re module.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).


1 Answers

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.

like image 109
Jon Avatar answered Oct 14 '22 17:10

Jon