正则表达式IfThenElse -匹配单个闭括号或不匹配括号
C++11 Regex IfThenElse - Single, closed brackets matched OR no brackets matched
我如何定义一个c++11/ECMAScript兼容的正则表达式匹配字符串:
-
包含一个长度大于0的字母数字字符串的封闭圆括号,例如regex语句
"(w+)"
,它正确匹配"(abc_123)"
而忽略不正确的"(abc_123"
,"abc_123)"
和"abc_123"
。但是,上述表达式不会忽略包含多个平衡/不平衡括号的输入字符串-我想从匹配结果中排除"((abc_123)"
,"(abc_123))"
和"((abc_123))"
。 -
或单个字母数字单词,没有任何不平衡的括号-例如,像regex语句
"w+"
正确匹配"abc_123"
,但不幸的是错误地匹配"(abc_123"
,"abc_123)"
,"((abc_123)"
,"(abc_123))"
和"((abc_123))"
…
为清楚起见,上面每个测试用例所需的匹配是:
-
"abc_123"
= Match, -
"(abc_123)"
= Match, -
"(abc_123"
=不匹配, -
"abc_123)"
=不匹配, -
"((abc_123)"
=不匹配, -
"(abc_123))"
=不匹配, -
"((abc_123))"
=不匹配。
我一直在玩实现http://www.regular-expressions.info/conditional.html建议的IfThenElse格式,但还没有走得很远…是否有某种方法可以限制特定组的出现次数[例如"((){0,1}"
匹配零或一个左圆括号],并将前一组的重复次数传递给后一组[例如"num1"
等于"("
括号出现在"((){0,1}"
中的次数,然后我可以将其传递给相应的右括号组,"()){num1}"
说…]
我想这不是你想要的,也不是很优雅,但是…
使用"or"(|
),您应该获得基于"\(\w+\)|\w+"
的总比没有好。
完整的示例如下
#include <regex>
#include <iostream>
bool isMatch (std::string const & str)
{
static std::regex const
rgx { "\(\w+\)|\w+" };
std::smatch srgx;
return std::regex_match(str, srgx, rgx);
}
int main()
{
std::cout << isMatch("abc_123") << std::endl; // print 1
std::cout << isMatch("(abc_123)") << std::endl; // print 1
std::cout << isMatch("(abc_123") << std::endl; // print 0
std::cout << isMatch("abc_123)") << std::endl; // print 0
std::cout << isMatch("((abc_123)") << std::endl; // print 0
std::cout << isMatch("(abc_123))") << std::endl; // print 0
std::cout << isMatch("((abc_123))") << std::endl; // print 0
}
相关文章:
- Qt SQLite没有查询或参数计数不匹配
- 模板参数推导失败,函数参数/参数不匹配
- 在使用累加时,C++中的运算符+不匹配
- C++ 与操作员不匹配<<
- 在 Arduino 上使用 sscanf 会导致与 const char * 不匹配,并且返回值始终相同,尽管输入值不同
- 与'operator='不匹配(操作数类型'String'且"void")
- C++模板/别名 - 模板参数列表中参数 1 处的类型/值不匹配
- C4018:类内有符号、无符号不匹配
- 我在 .h 中有一个枚举类,并且在.cpp错误中有一个运算符重载:与"运算符<<不匹配
- 为什么我收到错误:"运算符<<不匹配?
- RE2 不匹配非 ASCII 字符
- 函数签名与调用的函数不匹配,常量字符[]和字符*之间的区别?
- 模板推导:为什么函数指针模板定义在常量和/或引用时不匹配?
- 错误:"模板<类_Tp,类_Dp>类 std::unique_ptr"的模板参数列表中参数 1 的类型/值不匹配
- OpenSSL fips in C++ wrapper Library 如何?错误:指纹不匹配
- 为什么我的数组值与此处的全局变量不匹配?
- 引号之间匹配/不匹配,带有不可避免的引号和多行
- 映射迭代器与运算符不匹配
- 正则表达式IfThenElse -匹配单个闭括号或不匹配括号
- 我可以在c++ switch语句中匹配一个范围而不是单个值吗?