Home > Enterprise >  Regex to match a "global::" prefixed fully qualified C# type name
Regex to match a "global::" prefixed fully qualified C# type name

Time:01-07

I'm trying to match fully qualified C# type names, but the after \w captures too much:

global((::|\.)\w (?!\s|\()) 

Tried to play with quantifiers and negative lookahead but without success.

Online sandbox:

https://regex101.com/r/L6Y8kv/1

Sample:

    public global::libebur128.EBUR128StateInternal D
    {
        get
        {
            var __result0 = global::libebur128.EBUR128StateInternal.__GetOrCreateInstance(((__Internal*)__Instance)->d, false);
            return __result0;
        }

Result:

global::libebur128.EBUR128StateInterna
global::libebur128.EBUR128StateInternal.__GetOrCreateInstanc

Expected:

global::libebur128.EBUR128StateInternal
global::libebur128.EBUR128StateInternal

CodePudding user response:

For the example data, you might use:

\bglobal::[^\W_] (?:\.[^\W_] )*

The pattern matches:

  • \bglobal:: A word boundary, followed by matching global::
  • [^\W_] Match 1 word characters excluding _
  • (?:\.[^\W_] )* Optionally repeat matching . and 1 word characters excluding _

See a regex101 demo.

If the last part should not be followed by ( and you don't want to take the underscore into account, you might add a word boundary and a negative lookahead:

\bglobal::\w (?:\.\w )*\b(?!\()

The pattern matches:

  • \b A word boundary
  • global:: Match literally
  • \w Match 1 word chars
  • (?:\.\w )* Optionally repeat . and 1 word chars
  • \b A word boundary (to prevent backtracking to make the next assertion true)
  • (?!\() Negative lookahead, assert not ( directly to the right of the current position

regex101 demo

  • Related