Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex/Method to remove namespace from a Type.FullName - C#

Tags:

c#

regex

I am working on writing a method to remove the namespace from a System.Type.FullName (not XML).

I started off googling and didn't get too far so switched to trying to write a Regex I could use with a Regex.Replace(). But I am far from a master of the Regex arts, so I present myself humbly before the regex gods.

Given the following inputs:

name.space.class
name.space.class<other.name.space.class1>
name.space.class<other.name.space.class1, shortSpace.class2>

I need to remove the namespaces so I get:

class
class<class1>
class<class1, class2>

Alternatively, if anyone knows of an existing library that has this functionality, all the better!

Note: I know System.Type has a Namespace property that I could use to remove the namespace (ie System.Type.FullName - System.Type.Namespace), but my method takes a type name as a string and needs to work with type names that the run-time does not know about (can't resolve).

like image 557
Philip Pittle Avatar asked Jan 14 '23 07:01

Philip Pittle


1 Answers

How about this...

[.\w]+\.(\w+)

...and substiuting with $1. See it in action on regex101.

From looking at some C# examples it seems you would do

string output = Regex.Replace(input, @"[.\w]+\.(\w+)", "$1");
like image 180
zb226 Avatar answered Jan 29 '23 00:01

zb226