-2

I am trying to write the RegEx for replacing "name" part in below string.

 \profile\name\details

Where name: -Can have special characters -No spaces

Let's say I want to replace "name" in above path with ABCD, the result would be

 \profile\ABCD\details

What would be the RegEx to be used in Replace for this?
I have tried [a-zA-Z0-9@#$%&*+\-_(),+':;?.,!\[\]\s\\/]+$ but it's not working.

Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41
user7784348
  • 265
  • 2
  • 11

1 Answers1

4

As your dynamic part is surrounded by two static part you can use them to find it.

\\profile\\(.*)\\details

Now if you want to replace only the middle part you can either use LookAround.

string pattern = @"(?<=\\profile\\).*(?=\\details)";
string substitution = @"titi";
string input = @"\profile\name\details
\profile\name\details
";
RegexOptions options = RegexOptions.Multiline;

Regex regex = new Regex(pattern, options);
string result = regex.Replace(input, substitution);

Or use the replacement patterns $GroupIndex

string pattern = @"(\\profile\\)(.*)(\\details)";
string substitution = @"$1Replacement$3";
string input = @"\profile\name\details
\profile\name\details
";
RegexOptions options = RegexOptions.Multiline;

Regex regex = new Regex(pattern, options);
string result = regex.Replace(input, substitution);

For readable nammed group substitution is a possibility.

Drag and Drop
  • 2,672
  • 3
  • 25
  • 37
  • I didn't address the special characters set you had in your original question but you can simply use it in those regex. I will recommend using the second may it a little bit more readable when regex is complex. If you need extra information about $ substitution I recommend [MSDN documentation](https://learn.microsoft.com/en-us/dotnet/standard/base-types/substitutions-in-regular-expressions) – Drag and Drop Aug 30 '18 at 08:02
  • Recommending MSDN:) – yusuf hayırsever Jan 20 '21 at 13:15
  • I find MSDN just fine. Alll msdn link go dead every 4-5 years when they rebuild the documentation. And the github of the documentation is quite active making many anchor go dead. (fixed one in this answer). But it's a good source of information. If I had to pick one static source of information it will the the MSDN and referencesource.microsoft.com other StackOverflow. – Drag and Drop Jan 20 '21 at 14:29
  • Microsoft TechNet, then MSDN. But now it's Microsoft Doc (learn.microsoft.com). I stop following the rebranding in 2015 – Drag and Drop Jan 20 '21 at 14:30