简体   繁体   中英

C# RegEx - Replace Match Groups?

can't find clean way to do this - just want to replace the two matched strings - but every example is pretty hacky (use substrings to split up string based on matches??), isn't there a clean way to just replace the two matched groups in a string?? thanks

var inLine = "Project(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"Common\", \"Libraries\\Common\\Common.csproj\", \"{91197577-34B9-4D46-B3FE-A8589D4380B1}\"";
var regex = new Regex("Project\\(\\\"{.*}\\\"\\) = \"(?<projectName>\\S*)\", \"(?<relativePath>\\S*)\", \"{.*}\"");
var newProjectName = "Blah";
var newRelativePath = "..\Core\Libraries\Blah\Blah.csproj";
var match = regex.Match(inLine);
if (match.Success)
{
    var projectName = match.Groups[1].Value;
    var relativePath = match.Groups[2].Value;
    var replaced = regex.Replace(inLine, m =>
       {
          // ??????????
          return ""; 
       });
    // want replaced to be:
    // Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Blah", "..\Core\Libraries\Blah\Blah.csproj", "{91197577-34B9-4D46-B3FE-A8589D4380B1}"
}

Edited post: Expected behavior is input string:

Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common", "Libraries\Common\Common.csproj", "{91197577-34B9-4D46-B3FE-A8589D4380B1}"

Want to replace Common and Libraries\Common\Common.csproj with 2 other strings like Blah and..\Core\Libraries\Blah\Blah.csproj so new string value (replaced) would be:

Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Blah", "..\Core\Libraries\Blah\Blah.csproj", "{91197577-34B9-4D46-B3FE-A8589D4380B1}"

I Googled a bit and found something interesting here

I adapted their solution a bit so it would fit the criteria. It appears to work rather nicely. Although I'm not sure if it is better than the remove insert method.

Here is my code:

var name = "Blah";
var location = "..\\Core\\Libraries\\Blah\\Blah.csproj";
var result = Regex.Replace(INPUT, "^(.*\")(\\w+)(\".*\")([\\w\\\\\\.]+)(\".*)$", m =>
    {
        return string.Join("",
                m.Groups.OfType<Group>().Select((g, i) =>
                {
                    switch (i)
                    {
                        case 1:
                            return g.Value;
                        case 2:
                            return name;
                        case 3:
                            return g.Value;
                        case 4:
                            return location;
                        default:
                            return g.Value;
                    }
                }).Skip(1).ToArray());
    });

Here is the fully working code on ideone

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM