正则表达式匹配c#中的所有资本和下划线

我需要找到只有大写字母和下划线的字符串中的所有单词

string str = "ABCD_EFG_LMNO hello world PQR_ST_UVW US Apple PQR__ZYZ PQR__LMN__ZYZ"; string pattern = "[A-Z_]+[_][AZ]+"; 

输出应该只在单词下面

 ABCD_EFG_LMNO PQR_ST_UVW 

使用字符类时,将忽略该顺序。 改为使用组:

 [AZ]+(?:_[AZ]+)+ 

regex101演示

这是你需要的吗?

 string strRegex = @"(?[AZ]+(?:_[AZ]+)+))"; Regex myRegex = new Regex(strRegex, RegexOptions.Multiline); string strTargetString = @"ABCD_EFG_LMNO hello world PQR_ST_UVW US Apple PQR__ZYZ PQR__LMN__ZYZ""" + "\n\n\n"; foreach (Match myMatch in myRegex.Matches(strTargetString)) { if (myMatch.Success) { // Add some displaying code } } 

提示:使用RegExHero for .NET尝试:)