【问题标题】:Regex to match all capital and underscore in c#正则表达式匹配c#中的所有大写和下划线
【发布时间】:2014-03-11 14:18:08
【问题描述】:

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

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  

【问题讨论】:

  • 而你当前的输出是...
  • 当前输出为 ABCD_EFG_LMNO PQR_ST_UVW PQR__ZYZ PQR__LMN__ZYZ
  • 是否应该匹配这个子字符串:ABC__DE_F901_R,即使不是可能的字符串?

标签: c# regex


【解决方案1】:

当您使用字符类时,顺序会被忽略。改用组:

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

regex101 demo

【讨论】:

  • +1 至少这更短了,结果证明我有一个小缺陷:)
  • 非常感谢它的工作,你能解释一下这个模式,特别是 (?:_[A-Z]+)
  • @AnsariTanveer _[A-Z]+ 应该很容易理解。它是一个下划线,后跟任意数量的大写字母。现在,如果你把它放入(?: ... )+,这意味着这个组(_[A-Z]+)正在通过量词+重复(意思是至少一次)。
【解决方案2】:

这是你需要的吗?

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
  }
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-16
    • 1970-01-01
    相关资源
    最近更新 更多