Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx - Match using symbols but don't replace them

Tags:

c#

regex

I would like to use a symbols in a RegEx pattern to find matches, but I don't want them replaced. This is for class and namespace manipulation in C#.

For example:

MyNamespaceLib.EntityDataModelTests.TestsMyClassTests+MyInnerClassTests

must be replaced as:

MyNamespaceLib.EntityDataModel.TestsMyClass+MyInnerClass

(Note, only "Tests" is replace when it appears at the end of the namespace part, and not when it's part of the class/namespace name)

I've managed to get the first part right in finding the matches, but I'm battling to keep the symbols in the replaced match.

So far I have:

var input = "MyNamespaceLib.EntityDataModelTests.TestsMyClassTests+MyInnerClassTests";

var output = Regex.Replace(input, "Tests[.+]|$", "");

I've tried using a non-capturing group, but I suspect it's not meant for the way I'm trying to use it.

Thanks!

like image 909
Steve Avatar asked Dec 24 '12 22:12

Steve


2 Answers

So what you want to do is replace matches not followed by a . or a +? Use a lookahead:

@"Tests(?![.+])"
like image 174
Ry- Avatar answered Sep 28 '22 08:09

Ry-


You can use the MatchEvaluator overload of the Regex.Replace method, where the string to replace the match with is generated on the fly. I get the special simbol in a capturing group (and the first capturing group is always Group1 of the match), and replace the match with the value, like this:

var output = Regex.Replace(input, @"Tests([.+]|$)", m => m.Groups[1].Value);

Also, per minitech's comment, you can also use $1 for the first capturing group in the (string, string) overload of Regex.Replace, like:

var output = Regex.Replace(input, @"Tests([.+]|$)", "$1");

That said, a regex is often write-only code, so you can always do a dumb and simple replace:

var output = input.Replace("Tests+","").Replace("Tests.","") ...;
like image 25
SWeko Avatar answered Sep 28 '22 07:09

SWeko