1

For the given xml formatted string

<ItemGroup>
    <PackageReference Include="Bond.CSharp" />
  </ItemGroup>

<ItemGroup>
    <PackageReference Include="Bond.CSharp" />
  </ItemGroup>

I am attempting to capture

<ItemGroup>
    <PackageReference

using the following Regex:

<ItemGroup>\s*<PackageReference

How can I limit the result to just the first match and not get both ItemGroups?

I am using C# flavored regex

I tried using

 (<ItemGroup>\s*<PackageReference)+? 

and

<ItemGroup>\s*<PackageReference{0,1}

but neither approach worked for me

1 Answer 1

1

You can use .* with the Singleline flag to consume all characters after the first match of <ItemGroup>\s*<PackageReference so that there won't be a second occurrence. Capture the desired portion in parentheses as a group:

Regex regex = new Regex(@"(<ItemGroup>\s*<PackageReference).*", RegexOptions.Singleline);
MatchCollection matches = regex.Matches(xml);
foreach (Match match in matches) {
    GroupCollection groups = match.Groups;
    Console.WriteLine(groups[0].Value)
}
Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately, this doesn't work for me. Using SingleLine yields a single Match incl all PackageReference. Removing single line gives me 1 match but with Include= <ItemGroup> <PackageReference Include="Bond.CSharp" />
It works by adding ? after the .* in your regex expression and removing singleLine. Thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.