简体   繁体   English

用于匹配“global::”前缀完全限定 C# 类型名称的正则表达式

[英]Regex to match a "global::" prefixed fully qualified C# type name

I'm trying to match fully qualified C# type names, but the + after \w+ captures too much:我正在尝试匹配完全限定的 C# 类型名称,但是 \w+ 之后的 + 捕获了太多:

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

Tried to play with quantifiers and negative lookahead but without success.尝试使用量词和负前瞻但没有成功。

Online sandbox:在线沙箱:

https://regex101.com/r/L6Y8kv/1 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

For the example data, you might use:对于示例数据,您可以使用:

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

The pattern matches:模式匹配:

  • \bglobal:: A word boundary, followed by matching global:: \bglobal::一个单词边界,后跟匹配的global::
  • [^\W_]+ Match 1+ word characters excluding _ [^\W_]+匹配除_以外的1+个单词字符
  • (?:\.[^\W_]+)* Optionally repeat matching . (?:\.[^\W_]+)*可选重复匹配. and 1+ word characters excluding _和 1+ 个单词字符,不包括_

See a regex101 demo .请参阅regex101 演示

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 \b单词边界
  • global:: Match literally global::逐字匹配
  • \w+ Match 1+ word chars \w+匹配 1+ 个单词字符
  • (?:\.\w+)* Optionally repeat . (?:\.\w+)*可选择重复. and 1+ word chars和 1+ 个单词字符
  • \b A word boundary (to prevent backtracking to make the next assertion true) \b单词边界(以防止回溯以使下一个断言为真)
  • (?!\() Negative lookahead, assert not ( directly to the right of the current position (?!\()否定lookahead,assert not (直接在当前position右边

regex101 demo regex101 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM