计数字符串中与模式匹配的令牌数量
Count number of tokens matching a pattern in a string
计算字符串中匹配一个模式的记号个数的方法。
token是"$"后面跟着"$$","$"answers"$$"之间可以有任意数目的字符。
例如:"$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;
}
看看如何使用
正则表达式。匹配方法(字符串)
在指定的输入字符串中搜索所有出现的正则表达式。
也可以看看正则表达式语言-快速参考
您可以使用以下正则表达式
$.*?$$
检测任何字符之间的字符数,甚至是零字符。如果至少需要一个字符,则将*
替换为+
。
正如@astander已经说过的,要检索匹配计数使用Regex.Matches
string input = "$122$$dddd$1aasds$$";
string pattern = @"$.*?$$";
Regex rgx = new Regex(pattern);
MatchCollection matches = rgx.Matches(input);
int count = matches.Count();
相关文章:
- 如何在C++中使用X509证书模在令牌中查找私钥
- holeMenuProgram.cpp:38:1 错误:'}'令牌之前的预期主表达式
- C++:"("令牌"之前有预期的非限定 id 指向类中成员函数的指针
- Arduino 用于语句错误。令牌之前的预期')' ';'。如何解决这个问题?
- 错误:令牌 { '{' 之前应存在非限定 ID
- 允许哪些令牌作为 #include 的参数?
- "错误 C0000:语法错误,令牌"<EOF>"处出现意外$end,并且不确定
- 它在 { 令牌之前给了我预期的标识符
- (错误:令牌之前'<<'预期的主表达式)
- 为什么 ## aka 令牌粘贴运算符不适用于 C 和 C++ 中的注释?
- 错误:"->"令牌之前的预期初始值设定项
- LINUX 操作系统上的错误:令牌之前预期的构造函数、析构函数或类型转换'('?
- 丢失读入的每一行输入中的最后一个令牌
- 模式匹配文本并提取C++中的数据
- 如何使用 libCurl 将访问令牌发送到服务器 API
- C++令牌定义成员
- 无法在硬件模式下创建 SGX 安全区 - "invalid launch token"即使文档将无效的启动令牌指定为第一个
- 如何使 Boost.Spirit.Lex 令牌值成为匹配序列的子字符串(最好通过正则表达式匹配组)
- 计数字符串中与模式匹配的令牌数量
- 访问flex扫描仪的内部缓冲区、长度和令牌匹配位置