import re
regex = re.compile(r"(<ProjectReference.*?Project2[\s\S]*?</ProjectReference>)", flags=re.MULTILINE)
test_str = (" <ProjectReference Include=\"..\\..\\Project1\\Project1\\Project1.csproj\">\n"
" <Project>{714c6b26-c609-40a4-80a9-421bd842562d}</Project>\n"
" <Name>Project1</Name>\n"
" </ProjectReference>\n\n\n"
" <ItemGroup>\n"
" <ProjectReference Include=\"..\\..\\Project2\\Project2.csproj\">\n"
" <Project>{6c2a7631-8b47-4ae9-a68f-f728666105b9}</Project>\n"
" <Name>Project2</Name>\n"
" </ProjectReference>\n"
" <ProjectReference Include=\"..\\..\\Project3\\Project3\\Project3.csproj\">\n"
" <Project>{39860208-8146-429f-a1d1-5f8ed2fd7f5f}</Project>\n"
" <Name>Project3</Name>\n"
" </ProjectReference>\n"
" <ProjectReference Include=\"..\\..\\Project4\\Project4.csproj\">\n"
" <Project>{58144d60-19d9-4d11-8ae6-088e03ccf874}</Project>\n"
" <Name>Project4</Name>\n"
" </ProjectReference>\n"
" <ProjectReference Include=\"..\\..\\Project5\\Project5.csproj\">\n"
" <Project>{33baa509-ad24-4a72-a2fc-8f297e75e90d}</Project>\n"
" <Name>Project5</Name>\n"
" </ProjectReference>\n"
" </ItemGroup>\n"
" <PropertyGroup>\n"
" <VisualStudioVersion Condition=\"'$(VisualStudioVersion)' == ''\">10.0</VisualStudioVersion>\n"
" <VSToolsPath Condition=\"'$(VSToolsPath)' == ''\">$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)</VSToolsPath>\n"
" </PropertyGroup>")
matches = regex.finditer(test_str)
for match_num, match in enumerate(matches, start=1):
print(f"Match {match_num} was found at {match.start()}-{match.end()}: {match.group()}")
for group_num, group in enumerate(match.groups(), start=1):
print(f"Group {group_num} found at {match.start(group_num)}-{match.end(group_num)}: {group}")
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Python, please visit: https://docs.python.org/3/library/re.html