R – Quick Regex question

regex

Can anybody guide me in the right direction…

I have some folder strucktures that I want to check for a trailing / slash, some of the folders don't have a trailing / and if it does not have a trailing
/ I need to add one

If I use this regex it works but it replace the last character of the folder name

    Folder/name/test
    folder/name/test1/
    folder/name/test2/
replace(/.$/ig,"/");

This regex replaces Folder/name/tes[t]/ but will take out the t and replace it with /

Hope this makes sense…

Best Solution

The regex you made basically means this: take any character that is the last one in the string and replace it with /. What you need to do is to group the last character and then insert it again in the replacement, like this:

replace(/([^\/])$/ig,"$1/");

For more information see http://www.regular-expressions.info/brackets.html

Related Question