Regex匹配c#中的所有大写和下划线

本文关键字:下划线 匹配 Regex | 更新日期: 2023-09-27 17:49:35

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

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

输出应该只在单词

下面
ABCD_EFG_LMNO 
PQR_ST_UVW  

Regex匹配c#中的所有大写和下划线

当您使用字符类时,顺序将被忽略。使用组代替:

[A-Z]+(?:_[A-Z]+)+

regex101演示

这是你需要的吗?

string strRegex = @"(?<base>[A-Z]+(?:_[A-Z]+)+))";
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
  }
}

提示:使用。net的RegExHero来尝试:)