正则表达式匹配有效的命名空间名称

问题描述:

我想这个问题被问过,但我想谷歌,但没有找到答案。也许我用错了关键字。

I thought this question was asked before but I tried Google but didn't find an answer. Maybe I used wrong keywords.

时有可能使用正则表达式匹配有效的C#命名空间名称?

Is it possible to use regular expression to match valid C# namespace name?

谢谢

更新:

谢谢大家对你的答案和研究!这个问题要复杂得多比我的预期。由于奥斯卡Mederos 乔伊指出,一个有效的命名空间不能包含C#保留关键字,并且可以包含更多的Unicode字符不是拉丁字母。

Thanks everyone for your answers and research! This question is much more complex than I expected. As Oscar Mederos and Joey pointed out, a valid namespace cannot contain C# reserved keywords, and can contain a lot more Unicode characters than Latin letters.

但我当前的项目只需要以语法验证命名空间。所以我接受 primfaktor 的答案,但我upvoted所有的答案。

But my current project only need to syntactically validate namespaces. So I accepted primfaktor's answer, but I upvoted all answers.

对于我来说,这个工作:

For me, this worked:

^using (@?[a-z_A-Z]\w+(?:\.@?[a-z_A-Z]\w+)*);$

它匹配使用C#行并返回第一个(也是唯一一个)匹配组完整的命名空间。您可能需要删除 ^ $ ,以便缩进和尾随注释。

It matches using lines in C# and returns the complete namespace in the first (and only) match group. You may want to remove ^ and $ to allow for indentation and trailing comments.

的例子在RegExr。

Example on RegExr.