c# - 计算与字符串中的模式匹配的标记数

标签 c# c++ regex pattern-matching

一种计算与字符串中的模式匹配的标记数量的方法。

token 是一个“$”后跟“$$”,“$”和“$$”之间可以有任意数量的字符。

例如:"$123$$, $ab$$, $qqwe123$$

输入字符串可以是 "$122$$dddd$1aasds$$"

对于上述字符串,该方法的输出应为 2。

编程语言可以是 C# 或 C++。

这是我想出的代码,但试图找到最好的方法:

static int CalculateTokenCount()
        {
            string s = "$ab$$ask$$$$123$$";
            int tokenCount = 0;
            bool foundOneDollar = false;
            bool foundSecondDollar = false;

            if (string.IsNullOrEmpty(s))
            {
                return tokenCount;
            }
            for (int i = 0, x = 0; i < s.Length; i++)
            {
                if (s[i] == '$' && !foundOneDollar)
                {
                    foundOneDollar = true;
                    continue;
                }

                if (foundOneDollar)
                {
                    if (s[i] == '$' && !foundSecondDollar)
                    {
                        foundSecondDollar = true;
                        continue;
                    }
                }

                if (foundSecondDollar)
                {
                    if (s[i] == '$')
                    {
                        tokenCount++;
                    }  
                    foundSecondDollar = false;
                }
            }
            Console.WriteLine(tokenCount);
            return tokenCount;
        }

最佳答案

看看使用类似的东西

Regex.Matches Method (String)

Searches the specified input string for all occurrences of a regular expression.

也可以看看 Regular Expression Language - Quick Reference

关于c# - 计算与字符串中的模式匹配的标记数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15587335/

相关文章:

用于匹配单词的正则表达式,除非前一行以单词结尾

c# - 与 Oracle 的连接通过控制台应用程序工作,而不通过 Web 服务工作

c# - 无法在引用 edmx 的项目上搭建脚手架

c# - $(this) 在 C# 中等效

c++ - cv::Mat::clone() 是否比分配由 cv::Mat::zeros() 创建的矩阵更有效?

C#/.NET 等同于 Java 的 Matcher.matches() 和 Matcher.lookingAt()

c# - Entity Framework : OrderBy() numeric property when mapped column type is textual

c++ - 用表达式包装可变参数宏中的每个元素

c++ - C++中如何检查字符串的结尾?

Javascript RegExp 替换为负前瞻