Search code examples
regexmsbuildmsbuildcommunitytasks

MSBuild Community Taks RegexReplace remove trailing slash from path


I am trying to use MSBuild community tasks to remove the slash from the end of the OutputPath

This is what i have so far.

<RegexReplace Input="$(OutputPath)" Expression="\$" Replacement="" Count="1">
 <Output ItemName="FormattedOutputPath" TaskParameter="Output" />
</RegexReplace>
<Message Text="@(FormattedOutputPath)"/>

Unfortunately the message just returns my path still with the slash on the end. The path is C:\MyDirectory\

It looks like my expression is incorrect

Can anyone help?


Solution

  • Slash is using as an escape character, so in pattern you have to escape slash character by another slash:

    <RegexReplace Input="$(OutputPath)" Expression="\\$" Replacement="" Count="1">
      <Output ItemName="FormattedOutputPath" TaskParameter="Output" />
    </RegexReplace>
    <Message Text="@(FormattedOutputPath)"/>
    

    To better understand escaping see the following examples:

    1. $ represents end of line/string
    2. \$ represents dollar sign character
    3. \\ represents slash character
    4. \\$ represents slash character at the end of line/string