Home > other >  MSBUILD RegexReplace get all text till 2nd last dot from end
MSBUILD RegexReplace get all text till 2nd last dot from end

Time:01-13

I am working with ToolsVersion="3.5".

I wanted to match from end of the string till 2-nd last dot (.).

For Example for given value 123.456.78.910.abcdefgh I wanted to get 910.abcdefgh only.

I tried with

<RegexReplace Input="$(big_number)" Expression="/(\w \.\w )$/gm" Replacement="$1" count="1">
        <Output ItemName ="big_number_tail" TaskParameter="Output"/>
</RegexReplace>

But it is returning entire string only. Any idea what went wrong ?

CodePudding user response:

First of all, do not use a regex literal in a text attribute. When you define regex via strings, not code, regex literal notation (like /.../gm) is not usually used and in these cases / regex delimiters and g, m, etc. flags are treated as part of a pattern, and as a result, it never matches.

Besides, when you extract via replacing as here, you need to make sure you match the whole string with your pattern, and only capture the part you want to extract. Note you may have more than 1 capturing group, and then you could use $2, $3, etc. in the replacement.

You can use

<RegexReplace Input="$(big_number)" Expression=".*\.([^.]*\.[^.]*)$" Replacement="$1" count="1">

See the regex demo. Details:

  • .* - any zero or more chars other than line break chars, as many as possible
  • \. - a . char
  • ([^.]*\.[^.]*) - Group 1 ($1 refers to this part): zero or more non-dot chars, a . char, and again zero or more chars other than dots
  • $ - end of string.
  •  Tags:  
  • Related