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

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

I started with googling and didn't go too far, so I switched to trying to write Regex, which I could use with Regex.Replace (). But I am far from a master of art in regular expression, so I humbly present myself to the gods of regular expressions.

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 namespaces to get:

 class class<class1> class<class1, class2> 

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

Note. . I know that System.Type has a Namespace property that I could use to remove a namespace (for example, System.Type.FullName - System.Type.Namespace), but my method accepts type name as a string and should work with type names which runtime does not know about (cannot decide).

+4
source share
5 answers

How about this ...

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

... and substituting $1 . See it in action on regex101 .

From a look at some C # examples, it seems you would do

 string output = Regex.Replace(input, @"[.\w]+\.(\w+)", "$1"); 
+5
source

Try the following:

 public static string RemoveNamespaces(string typename) { return string.Join("", Regex.Split(typename, @"([^\w\.])").Select(p => p.Substring(p.LastIndexOf('.') + 1))); } 
+2
source

I would not even consider using regular expressions for this. The imperative code here is pretty trivial, although it requires a bit of string-fu:

 public string RemoveNamespace(string typename) { if(typename.Contains("<") { var genericArguments = typename. // in reality, we need a substring before // first occurence of "<" and last occurence of ">" SubstringBetween("<", ">"). Split(','). Select(string.Trim). Select(RemoveNamespace); return RemoveNamespace(typename.SubstringBefore("<")) + "<" + string.Join(", ", genericArguments) + ">"; } else { return typename.Trim().SubstringAfterLastOccurenceOf("."); } } 
+1
source

Sounds good to use a positive look:

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

This pattern will match any number of words separated by dots or pluses, except the last in the sequence (short name of the type). Replacing matches with an empty string will remove all namespace prefixes.

+1
source

Why not separate with a period (.) And take only the last line

0
source

Source: https://habr.com/ru/post/1482385/


All Articles