Sergej Andrejev
Sergej Andrejev

Reputation: 9413

MSBuild getting property substring before underscore symbol

In MSBuild I have a property which value is Name_Something. How can I get name part of this property.

Upvotes: 23

Views: 14991

Answers (3)

Julien Hoarau
Julien Hoarau

Reputation: 49970

With MSBuild 4

If you use MSBuild 4, you could use the new and shiny property functions.

<PropertyGroup>
  <MyProperty>Name_Something</MyProperty>
</PropertyGroup>

<Target Name="SubString">
  <PropertyGroup>
    <PropertyName>$(MyProperty.Substring(0, $(MyProperty.IndexOf('_'))))</PropertyName>
  </PropertyGroup>

  <Message Text="PropertyName: $(PropertyName)"/>
</Target>

With MSBuild < 4

You could use the RegexReplace task of MSBuild Community Task

<PropertyGroup>
  <MyProperty>Name_Something</MyProperty>
</PropertyGroup>

<Target Name="RegexReplace">
  <RegexReplace Input="$(MyProperty)" Expression="_.*" Replacement="" Count="1">
    <Output ItemName ="PropertyNameRegex" TaskParameter="Output" />
  </RegexReplace>

  <Message Text="PropertyNameRegex: @(PropertyNameRegex)"/>
</Target>

Upvotes: 44

Todd
Todd

Reputation: 5117

If I understand your question correctly you are trying to get the substring of a MSBuild property. There is no direct way to do string manipulation in MSBuild, like in NAnt. So you have two options:

1). Create separate variables for each part and combine them:

<PropertyGroup>
  <Name>Name</Name>
  <Something>Something</Something>
  <Combined>$(Name)_$(Something)</Combined>
</PropertyGroup>

This works fine if the parts are known before hand, but not if you need to do this dynamically.

2). Write a customer MSBuild task that does the string manipulation. This would be your only option if it needed to done at runtime.

Upvotes: -3

Filburt
Filburt

Reputation: 18061

It looks like you could use Item MetaData instead of a Property:

<ItemGroup>
    <Something Include="SomeValue">
        <Name>YourName</Name>
        <SecondName>Foo</SecondName>
    </Something>
</ItemGroup>

Upvotes: -4

Related Questions