【问题标题】:Regex , Detect all strings preceded with a certain character正则表达式,检测所有以某个字符开头的字符串
【发布时间】:2014-03-09 08:53:33
【问题描述】:

如何在 c# 中检测所有以 '%' 或 '$' 开头的字符串?

编辑:

如果我有以下字符串,例如:

string  test =   "Shipments will cost $150USD , which representes a rise of %34 ."

如何使用正则表达式检测$150USD%34

【问题讨论】:

  • 是的,例如如果我有字符串 "$150USD" 我如何使用正则表达式检测它?
  • 查看我的答案。很简单

标签: c# .net regex


【解决方案1】:

如果您的意思是查找所有单词,则可以使用该正则表达式。

(?<=\s?)[%$]\w+(?=\s?)

所以在Shipments will cost $150USD, which representes a rise of %34. 中会找到$150USD%34

C#代码是:

String subjectString = "Shipments will cost $150USD, which representes a rise of %34.";
var matches = Regex.Matches(subjectString, @"(?<=\s?)[%$]\w+(?=\s?)");

foreach (Match match in matches)
{
    var value = match.Value;
}

【讨论】:

  • 我必须使用哪个正则表达式函数?正则表达式匹配?
  • Matches 因为您需要所有匹配项,而不仅仅是第一个。
【解决方案2】:

就这么简单:

string s = "Shipments will cost $150USD , which representes a rise of %34 .";
            var matches = Regex.Matches(s, @"(\$|%)\w+");
            for (int i = 0; i < matches.Count; i++)
            {
                Console.WriteLine(matches[i].Value);
            }

【讨论】:

  • 是的,这也很好(而且更简单)。不过,您可以使用非捕获组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-13
  • 2015-12-11
  • 2011-09-16
  • 2017-07-24
  • 2021-11-04
相关资源
最近更新 更多